第一步:創(chuàng)建多語言資源文件步驟
第二步:Application設(shè)置加載語言(適配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()
}
}
/**
* 設(shè)置加載語言
*/
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設(shè)置加載語言(適配8.0及以上)
open class BaseActivity : FragmentActivity() {
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(newBase)
setLanguage()
}
/**
* 設(shè)置加載語言
*/
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)
}