当设备默认语言不是英语时,更改不起作用的语言



当我的设备语言不是英语(例如葡萄牙语(时,我无法更改语言。这是我的代码:

Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config,
context.getResources().getDisplayMetrics());

我检查了一些其他类似的asnwer,但它不太工作

SharedPrefUtils.saveLocale(locale); // optional - Helper method to save the selected language to SharedPreferences in case you might need to attach to activity context (you will need to code this)
Resources resources = getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
configuration.setLocale(locale);
} else{
configuration.locale=locale;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
getApplicationContext().createConfigurationContext(configuration);
} else {
resources.updateConfiguration(configuration,displayMetrics);
}

那我的问题是什么?

您需要将新的配置上下文传递给ContextWrapper超类。

在活动中覆盖attachBaseContext,并将新上下文作为-传递

@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(updatedConfigurationContext(base));
}

并从返回新上下文getApplicationContext().createConfigurationContext(configuration);

正如你在上面所做的。

您可能需要在更改默认区域设置后重新创建活动。

getActivity().recreate();

不知道你想在哪里做这件事,所以我只是假设它在一个活动中。这个答案也在Kotlin中,如果你想在Java中使用,请查看以下帖子:如何将kotlin源文件转换为java源文件

活动

override fun attachBaseContext(ctx: Context?) {
super.attachBaseContext(ContextWrapper.wrap(ctx, yourLocale))
}

ContextWrapper

class ContextWrapper(context: Context?) : android.content.ContextWrapper(context) {
companion object {
fun wrap(context: Context?, locale: Locale): ContextWrapper {
val configuration = context?.resources?.configuration
configuration?.setLocale(locale)
if (Build.VERSION.SDK_INT >= 24) {
val localeList = LocaleList(locale)
LocaleList.setDefault(localeList)
configuration?.locales = localeList
}
val ctx = if(configuration != null) context.createConfigurationContext(configuration) else null
return ContextWrapper(ctx)
}
}
}

重新创建上下文(活动(

在"活动"中使用recreate()重新启动"活动"上下文。

最新更新