受多种代码启发(例如:我们的Stackoverflow团队(向大家喊话)),我已经制作出了一个更简单的版本。扩展 ContextWrapper
是不必要的。
首先,假设你有两个按钮用于两种语言,英语和高棉语。在按钮的onClick事件中将语言代码保存到 SharedPreferences
中,然后调用活动的 recreate()
方法。
示例:
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.btn_lang_en:
break;
case R.id.btn_lang_kh:
break;
default:
break;
}
getActivity().recreate();
}
然后创建一个静态方法,返回ContextWrapper
,可以在Utils类中实现(因为这就是我做的,哈哈)。
public static ContextWrapper changeLang(Context context, String lang_code){
Locale sysLocale;
Resources rs = context.getResources();
Configuration config = rs.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
sysLocale = config.getLocales().get(0);
} else {
sysLocale = config.locale;
}
if (!lang_code.equals("") && !sysLocale.getLanguage().equals(lang_code)) {
Locale locale = new Locale(lang_code);
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
config.setLocale(locale);
} else {
config.locale = locale;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
context = context.createConfigurationContext(config);
} else {
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
}
return new ContextWrapper(context);
}
最后,在所有活动的attachBaseContext(Context newBase)
方法中,从SharedPreferences
加载语言代码。
@Override
protected void attachBaseContext(Context newBase) {
String lang_code = "en";
Context context = Utils.changeLang(newBase, lang_code);
super.attachBaseContext(context);
}
福利:为了避免手汗淋漓地敲键盘,我创建了一个LangSupportBaseActivity
类,它继承自Activity
并使用那里的最后一段代码。而我让所有其他活动都扩展LangSupportBaseActivity
。
示例:
public class LangSupportBaseActivity extends Activity{
...blab blab blab so on and so forth lines of neccessary code
@Override
protected void attachBaseContext(Context newBase) {
String lang_code = "en";
Context context = Utils.changeLang(newBase, lang_code);
super.attachBaseContext(context);
}
}
public class HomeActivity extends LangSupportBaseActivity{
...blab blab blab
}