在AndroidManifest.xml中,将此属性添加到您的Activity中
android:configChanges="locale"
在你的活动中覆盖onConfigurationChanged()
@Override public void onConfigurationChanged(Configuration newConfig) { // refresh your views here super.onConfigurationChanged(newConfig); }
我认为问题是在运行时为应用程序切换语言并在UI中显示本地化消息。 android:configChanges="locale"调用onConfigurationChanged如果在应用程序运行时更改了系统区域设置(在设备设置中),而不是在应用程序代码中更改区域设置,我想这就是你想要完成的。 这就是为什么它不令人耳目一新。
这是我在每个活动onCreate()或onResume()期间使用的方法,具体取决于我的需要(如果我的活动将在用户更改语言设置后恢复,或者将始终使用已设置的语言创建):
从那里我只是手动或从onConfigurationChanged()刷新视图,该方法在此方法完成后调用。
public static void changeLocale(Activity activity, String language) { final Resources res = activity.getResources(); final Configuration conf = res.getConfiguration(); if (language == null || language.length() == 0) { conf.locale = Locale.getDefault(); } else { final int idx = language.indexOf('-'); if (idx != -1) { final String[] split = language.split("-"); conf.locale = new Locale(split[0], split[1].substring(1)); } else { conf.locale = new Locale(language); } } res.updateConfiguration(conf, null); }
我不知道为什么onConfigurationChanged() 。
嘿,sandis,你的意思是当你改变语言时, onConfigurationChanged()方法没有在你的活动中调用吗? 我遇到了同样的问题。 问题可能是这样的:当我们改变语言时,活动转到onDestroy() (你可以试试这个),所以没有人可以调用onConfigurationChanged() 。 当我们再次启动活动时,将调用onCreate() ,而不是onConfigurationChanged() 。 区域设置更改和方向更改可能有所不同。
public void settingLocale(Context context, String language) { Locale locale; Configuration config = new Configuration(); if(language.equals(LANGUAGE_ENGLISH)) { locale = new Locale("en"); Locale.setDefault(locale); config.locale = locale; }else if(language.equals(LANGUAGE_ARABIC)){ locale = new Locale("hi"); Locale.setDefault(locale); config.locale = locale; } context.getResources().updateConfiguration(config, null); // Here again set the text on view to reflect locale change // and it will pick resource from new locale tv1.setText(R.string.one); //tv1 is textview in my activity }
假设你正在通过类似的方式改变语言
private void updateLocale(@NonNull final Context context, @NonNull final Locale newLocale) { final Resources resources = context.getResources(); final DisplayMetrics displayMetrics = resources.getDisplayMetrics(); final Configuration configuration = resources.getConfiguration(); configuration.locale = newLocale; resources.updateConfiguration(configuration, displayMetrics); Locale.setDefault(newLocale); }
您需要在所有当前打开的活动中调用Activity.recreate() ,如果用户在未订阅android:configChanges="locale"更改了系统语言,则会发生这种情况。