【问题标题】:Android N - Change Locale in runtimeAndroid N - 在运行时更改语言环境
【发布时间】:2017-06-14 20:57:58
【问题描述】:

我有一个 android 应用程序,我想向其中添加一个简单的首选项屏幕,其中包含一个用于在语言(英语和葡萄牙语)之间切换的选项。我已经有了合适的字符串资源文件。

如果我在系统偏好设置中更改操作系统的主要语言,然后重新加载应用程序,它将使用该语言,但我希望能够通过偏好设置屏幕进行操作。

我在这里的其他问题中看到,在以前的 Android 版本中这样做要容易得多,但现在不推荐使用该代码,因此我遵循了在每个活动中覆盖 attachBaseContext 方法的方法,以便通过 a 重新创建上下文我在其中加载当前在首选项中选择的语言环境的包装器,如本文所示:

Android N change language programatically

public class TCPreferenceActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {


@Override
public void onBuildHeaders(List<Header> target) {
    loadHeadersFromResource(R.xml.headers_preference, target);
}

@Override
protected boolean isValidFragment(String fragmentName) {
    return TCPreferenceFragment.class.getName().equals(fragmentName);
}


@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals("lang")) {
        recreate();
    }
}



@Override
protected void attachBaseContext(Context newBase) {

    SharedPreferences pref =  PreferenceManager.getDefaultSharedPreferences(newBase);

    String lang = pref.getString("lang", null);

    Locale locale = new Locale(lang);

    Context context = TCContextWrapper.wrap(newBase, locale);
    super.attachBaseContext(context);
}

}

所以据我了解,在更改首选项时,会调用 onSharedPreferenceChanged 方法。我在那里重新创建活动,以便可以使用新上下文重新启动它。

这是我的上下文包装器:

public class TCContextWrapper extends ContextWrapper {

public TCContextWrapper(Context base) {
    super(base);
}

public static ContextWrapper wrap(Context context, Locale newLocale) {

    Resources res = context.getResources();
    Configuration configuration = res.getConfiguration();

    if (android.os.Build.VERSION.SDK_INT >= 24) {
        configuration.setLocale(newLocale);

        LocaleList localeList = new LocaleList(newLocale);
        LocaleList.setDefault(localeList);
        configuration.setLocales(localeList);

        context = context.createConfigurationContext(configuration);


    } else if (android.os.Build.VERSION.SDK_INT >= 17) {
        configuration.setLocale(newLocale);
        context = context.createConfigurationContext(configuration);

    } else {
        configuration.locale = newLocale;
        res.updateConfiguration(configuration, res.getDisplayMetrics());
    }

    return new ContextWrapper(context);
}

}

调试我可以看到调用了 onChange 方法,重新创建了首选项活动,调用了上下文包装器,在包装器中正确创建了新的语言环境值,但是随着活动的启动,我一直看到相同的默认字符串。

有什么想法吗?

【问题讨论】:

    标签: java android locale android-preferences android-7.0-nougat


    【解决方案1】:

    您为Locale 对象设置的Language@parameter 应该是

    An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
         * up to 8 characters in length.
    

    根据文档。 因此,如果您使用其他东西,您将看不到更新的语言环境。

    【讨论】:

    • 就是这样,Gunhan,谢谢。
    猜你喜欢
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    相关资源
    最近更新 更多