我在手动更改应用程序语言时遇到了麻烦,在应用程序中,我为用户提供了将应用程序语言更改为他们喜欢的语言的功能,下面的代码即使在 Android
中也能正常工作(< strong>Pixel 3 模拟器),但由于某种原因,它无法在所有三星设备上运行
Context context = LocaleUtils.setLocale(getApplicationContext(), languageCode);
Resources resources = context.getResources();
Locale myLocale = new Locale(languageCode);
DisplayMetrics dm = resources.getDisplayMetrics();
Configuration conf = resources.getConfiguration();
conf.locale = myLocale;
resources.updateConfiguration(conf, dm);
Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(
getBaseContext().getPackageName());
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
应用程序类:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
LocaleUtils.onAttach(base, Locale.getDefault().getLanguage());
MultiDex.install(this);
}
每个 Activity :
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(ViewPumpContextWrapper.wrap(LocaleUtils.onAttach(newBase)));
}
最佳答案
甚至在 Android 10 之前,我就一直在努力解决三星设备上的动态区域设置更改问题。
现在可能有更好的解决方案,
但当时除了你所做的之外,
我最终通过以下方式通过资源标识符检索所有字符串:
public static String getStringByIdentifier(final Context context, final String stringResIdName, final boolean forceRefresh) {
final Resources res = getResources(context, forceRefresh);
String result;
try {
result = res.getString(res.getIdentifier(stringResIdName, "string",
context.getPackageName()));
} catch (final Resources.NotFoundException e) {
result = stringResIdName; // TODO or here you may throw an Exception and handle it accordingly.
}
return result;
}
public static String getStringByIdentifier(final Context context, final String stringResIdName) {
return getStringByIdentifier(context, stringResIdName, false);
}
private static Resources getResources(final Context context, final boolean refreshLocale) {
if (!refreshLocale) {
return context.getResources();
} else {
final Configuration configuration = new Configuration(context.getResources().getConfiguration());
configuration.setLocale(Locale.getDefault());
return context.createConfigurationContext(configuration).getResources();
}
}
所以你必须用下面的方式设置文本:
textView.setText(AndroidUtils.getStringByIdentifier(context, "string_res_name"));
对应的字符串资源在哪里:
<string name="string_res_name">Some string</string>
关于java - 手动更改语言在三星设备上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60591631/