【发布时间】:2020-01-18 17:00:24
【问题描述】:
我已阅读有关在运行时更改应用内语言的所有内容。目前一切都适用于 API 26+27+28+29(是的,我已经测试了所有这些),并在 API 25 及更低版本开始中断。 Now the only thing I know that happened in API level 26 was that application and activities no longer share the same resources (aka the top level resources) by default. And also that updateConfiguration for Resources gets deprecated in favor of createConfigurationContext in API 25
但是,这确实给了我零线索。
这是我的代码:
public class BaseApp extends MultiDexApplication { //for MinSDK < 21, otherwise "extends Application"
@Override
public void onCreate() {
LocaleHelper.updateResources(this);
super.onCreate();
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.updateResources(base));
MultiDex.install(this); /* Needed as per (@link MultiDexApplication) */
}
@Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
LocaleHelper.updateResources(this);
}
基础活动:
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.updateResources(base));
}
助手类:
class LocaleHelper {
static Context updateResources(Context context) {
Resources resources = context.getResources();
Configuration config = new Configuration(resources.getConfiguration());
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String lang = preferences.getString(Constants.PREF_KEY_LOCALE_OVERRIDE, Constants.PREF_VALUE_LOCALE_SYSTEM);
Locale locale = new Locale(lang);
if (Build.VERSION.SDK_INT >= 17) {
config.setLocale(locale);
context = context.createConfigurationContext(config);
} else {
config.locale = locale;
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
return context;
}
【问题讨论】:
-
这个答案对我有用check this
-
现在面临同样的问题..有什么更新吗??
-
有什么解决办法吗?
-
如我所见,您可能忘记调用 Locale.setDefault(locale)
-
我终于自己解决了这个问题。 github.com/YarikSOffice/LanguageTest/issues/6 1.1.0 appcompat有问题,所以我已经更新到下一个版本(现在是1.2.0-rc01)
标签: android configuration locale android-resources android-context