java - 更改应用程序区域设置运行时
问题描述
我想更新语言选择的应用程序区域设置。
主要活动:
@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);
选择后重定向到下一个屏幕,但语言没有更新。如果我重新启动应用程序,它会更新。
我怎样才能解决这个问题?
解决方案
这段代码适用于我
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);
推荐阅读
- elasticsearch - 如何通过在logstash中减去给定的年、月、日来计算从今天开始的旧日期?
- docker - NGINX 为什么 $request_uri 在 location 指令中破坏 proxy_pass?
- r - 如何将本地图像放入 Shiny 模态中?
- html - “底部:0px;”不工作也不“位置:粘性;”工作
- python - Curvefit() 没有正确拟合我的数据。如何给一个好身材?
- flutter - 在 Flutter 中实现 SearchBar
- javascript - 如何在javascript中操作对象数组
- flutter - 如何像这张图片一样让孩子集中在自定义油漆上?
- php - 仅使用 PHP 获取一组值循环和数组
- r - 数值和图例范围不匹配