第一步:创建多语言资源文件步骤
image.png
第二步:Application设置加载语言(适配7.0及以下)
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
//7.0以下加载此方法
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
setLanguage()
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
//7.0以下加载此方法
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
setLanguage()
}
}
/**
* 设置加载语言
*/
private fun setLanguage() {
val localconfig = SPUtils.spUtils.get(applicationContext, MyParms.LANGUAGE,"") as String
val config = resources.getConfiguration()
val metrics = resources.getDisplayMetrics()
var mlocale: Locale? = null
if (null != localconfig && !"".equals(localconfig)) {
mlocale = Locale(localconfig);
} else {
mlocale = Locale.getDefault();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
config.setLocale(mlocale)
}else{
config.locale = mlocale
}
resources.updateConfiguration(config, metrics)
}
}
第三步:activity设置加载语言(适配8.0及以上)
open class BaseActivity : FragmentActivity() {
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(newBase)
setLanguage()
}
/**
* 设置加载语言
*/
private fun setLanguage() {
val localconfig = SPUtils.spUtils.get(applicationContext, MyParms.LANGUAGE,"") as String
val config = resources.getConfiguration()
val metrics = resources.getDisplayMetrics()
var mlocale: Locale? = null
if (null != localconfig && !"".equals(localconfig)) {
mlocale = Locale(localconfig);
} else {
mlocale = Locale.getDefault();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
config.setLocale(mlocale)
}else{
config.locale = mlocale
}
resources.updateConfiguration(config, metrics)
}
}
第四步:切换语言
val config: Configuration = resources.configuration
val dm = resources.displayMetrics
when(chooseType){
1 ->{//中文简体
config.locale = Locale.SIMPLIFIED_CHINESE
}
2 ->{//english
config.locale = Locale.ENGLISH
}
}
resources.updateConfiguration(config, dm)
SPUtils.spUtils.put(this,MyParms.LANGUAGE,config.locale.getLanguage())
//这边不知道怎么回事儿,必须要阻塞几百毫秒才能切换成功
Thread.sleep(500)
//切换成功后必须要重启app,才能生效
restartApp(this, xxx::class.java)
WebView(this).destroy()
重启app代码
/**
* 重启app
*/
fun restartApp(activity: Activity, homeClass: Class<*>?) {
val intent = Intent(activity, homeClass)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
Process.killProcess(Process.myPid())
System.exit(0)
}
网友评论