首页 > 解决方案 > Android - 更改所有 Android 版本的应用程序语言

问题描述

我尝试了几种方法来更改 android 应用程序的语言环境,但是当我在 Android 7.0 或更低版本上测试我的应用程序时,语言环境没有改变。

注意:这些方法适用于 Android 8.0 或更高版本,但不适用于 Android 7.0 或更低版本。

哪种方式适用于所有 Android 版本?你知道吗?

我尝试过的方法:

注意:我在带有 Android 7.0 的 Galaxy Tab S2 上测试了我的应用程序(没有工作)。在装有 Android 8.0(已工作)的 Galaxy A5 2017 上。

注意:我的许多活动都是用 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 方法(我把这些代码放在我所有的活动中):

override fun attachBaseContext(base: Context?) {
    super.attachBaseContext(LocaleHelper.onAttach(base, "en"))
}

更改语言环境方法(到波斯语):

LocaleHelper.setLocale(getContext(), "fa")

标签: javaandroidxmlkotlinlocale

解决方案


例如,您应该创建一个基本活动并onConfigurationChange在其上覆盖方法,设置您保存在共享首选项中的默认语言。毕竟,您必须从基本活动扩展您的活动。


推荐阅读