我尝试了几种方法来更改 Android 应用程序的区域设置,但是当我在 Android 7.0 或更低版本上测试我的应用程序时,区域设置没有更改。
注意:这些方法适用于 Android 8.0 或更高版本,但不适用于 Android 7.0 或更低版本。
哪种方式适用于所有 Android 版本? 你知道吗?
我尝试过的方法:
注意:我在运行 Android 7.0 的 Galaxy Tab S2 上测试了我的应用程序(不起作用)。以及搭载 Android 8.0 的 Galaxy A5 2017(已运行)。
注意:我的许多 Activity 都是用 Kotlin 编写的。
我的代码:
区域设置助手类:
public class LocaleHelper {
private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
public static Context onAttach(Context context) {
String lang = getPersistedData(context, Locale.getDefault().getLanguage());
return setLocale(context, lang);
}
public static Context onAttach(Context context, String defaultLanguage) {
String lang = getPersistedData(context, defaultLanguage);
return setLocale(context, lang);
}
public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
}
public static Context setLocale(Context context, String language) {
persist(context, language);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
private static String getPersistedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}
private static void persist(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SELECTED_LANGUAGE, language);
editor.apply();
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
return context.createConfigurationContext(configuration);
}
@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
}
attachBaseContext 方法(我将这些代码放在我的所有 Activity 中):
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(LocaleHelper.onAttach(base, "en"))
}
更改语言环境方法(波斯语):
LocaleHelper.setLocale(getContext(), "fa")
最佳答案
例如,您应该创建一个基本 Activity 并重写其上的 onConfigurationChange
方法,设置您在共享首选项中保存的默认语言。毕竟,您必须从基本 Activity 中扩展您的 Activity 。
关于java - Android - 更改所有 Android 版本的应用程序语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59319426/