更改项目包名称后,本地化无法在android上运行

时间:2019-12-15 07:12:59

标签: android localization localizable.strings

我已经在android中实现了本地化,以使用户可以在运行时使用以下代码更改应用的语言:

1-首先,我将用户选择的语言代码保存到共享的首选项中,例如,用户从英语切换到法国,然后重新启动应用程序。

一切正常,直到我将软件包名称从“ com.old.packagename”更改为“ com.new.packagename”。

appPreferenceHelper.setSelectedLanguage(getString(R.string.fr))
 val intent = Intent(this, SplashActivity::class.java)
            startActivity(intent)
            finishAffinity()

BaseActivity:

open class BaseActivity : AppCompatActivity() {


override fun attachBaseContext(base: Context?) {
    base?.let {applicationContext ->
        val selectedLanguage  = AppPreferenceHelper.getInstance(applicationContext).getSelectedLanguage()
        val locale = Locale(selectedLanguage)
        Locale.setDefault(locale)
        selectedLanguage?.let {
            super.attachBaseContext(CustomContextWrapper.wrap(applicationContext,locale))
        }
    }
}
}

CustomContextWrapper:

class CustomContextWrapper(base: Context?) : ContextWrapper(base) {
companion object {
    fun wrap(context: Context, newLocale: Locale): ContextWrapper {
        var mContext = context
        val res = mContext.resources
        val configuration = res.configuration

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            configuration.setLocale(newLocale)
            val localList = LocaleList(newLocale)
            LocaleList.setDefault(localList)
            configuration.locales = localList
            mContext = mContext.createConfigurationContext(configuration)
        } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(newLocale)
            mContext = mContext.createConfigurationContext(configuration)
        } else {
            configuration.locale = newLocale
            res.updateConfiguration(configuration, res.displayMetrics)
        }
        return ContextWrapper(mContext)
    }
}
}
  

-note:每个活动都来自BaseActivity

0 个答案:

没有答案
相关问题