Android11 修改系统语言
1.定义一个view
<RelativeLayout
android:id="@+id/rlChooseLanguage"
style="@style/SettingAboutItem">
<TextView
style="@style/SettingAboutItemTextView"
android:text="@string/choose_language" />
<ImageView style="@style/SettingAboutArrowImageView" />
</RelativeLayout>
2.java代码中给该view设置点击事件
private void showChooseLanguageDialog() {
final String[] languages = {getString(R.string.language_chinese), getString(R.string.language_english)};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.choose_language))
.setSingleChoiceItems(languages, getCurrentLanguageIndex(), (dialog, which) -> {
final String selectedLanguage = languages[which].equals(getString(R.string.language_chinese)) ? "zh" : "en";
dialog.dismiss();
ToastUtil.show(getString(R.string.language_waitting));
if (!selectedLanguage.equals(getCurrentLanguage())) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
changeAppLanguage(selectedLanguage);
restartApp();
}
}, 500);
}
})
.show();
}
private String getCurrentLanguage() {
Locale currentLocale = getResources().getConfiguration().locale;
return currentLocale.getLanguage();
}
private int getCurrentLanguageIndex() {
if (getCurrentLanguage().equals("zh")) {
return 0;
} else if (getCurrentLanguage().equals("en")) {
return 1;
}
return 0;
}
<string name="choose_language">选择语言</string>
<string name="language_chinese">中文</string>
<string name="language_english">英文</string>
<string name="language_waitting">修改配置中,请稍候...</string>
3.使用反射,调用修改语言功能
//设置语言,使用反射
public void changeAppLanguage(String languageCode) {
Locale locale = new Locale(languageCode);
try {
Class localPicker = Class.forName("com.android.internal.app.LocalePicker");
Method updateLocale = localPicker.getDeclaredMethod("updateLocale",
Locale.class);
updateLocale.invoke(null, locale);
} catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException
| IllegalAccessException e) {
e.printStackTrace();
}
}
4.如果设备直接修改Locale信息无效,且使用反射也无效,可以直接跳转到系统设置页面,引导用户修改语言
Intent intent = new Intent(Settings.ACTION_LOCALE_SETTINGS);
startActivity(intent);
5.重启app代码
private void restartApp() {
Intent intent = MyApplication.getInstance().getPackageManager().getLaunchIntentForPackage(MyApplication.getInstance().getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
System.exit(0); // 强制退出当前进程
}