首页 > 解决方案 > 更改应用程序区域设置运行时

问题描述

我想更新语言选择的应用程序区域设置。

主要活动:

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(LocaleHelper.onAttach(context));
}

选择语言的主要活动中的片段。在选择时,我写了以下代码:

private View.OnClickListener updateLanguage() {
    return (View v) -> {
        String code = v.getTag() != null ? v.getTag().toString() : getString(R.string.en_code);

        LocaleHelper.setLocale(getContext(), code);
        navController.navigate(R.id.action_languageFragment_to_instructionFragment);
    };
}

在选择语言时,我正在使用以下代码更新语言环境:

Locale locale = new Locale(language);
Locale.setDefault(locale);

Resources resources = context.getResources();
Configuration config = resources.getConfiguration();
config.setLocale(locale);

return context.createConfigurationContext(config);

选择后重定向到下一个屏幕,但语言没有更新。如果我重新启动应用程序,它会更新。

我怎样才能解决这个问题?

标签: javaandroid

解决方案


这段代码适用于我

       Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        if (Build.VERSION.SDK_INT < 17){ config.locale = new Locale(localecode.toLowerCase()); }
        else { config.setLocale(new Locale(localecode.toLowerCase())); }
        resources.updateConfiguration(config, dm);

推荐阅读