我有一个支持多种语言的旧项目。我想升级支持库和目标平台,在迁移到Androidx之前,一切正常,但现在更改语言无效!
我使用此代码更改App的默认语言环境
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);
}
Run Code Online (Sandbox Code Playgroud)
并在每个活动上通过attachBaseContext这样的覆盖调用此方法:
@Override
protected void attachBaseContext(Context newBase)
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String language = preferences.getString(SELECTED_LANGUAGE, "fa");
super.attachBaseContext(updateResources(newBase, language));
}
Run Code Online (Sandbox Code Playgroud)
我尝试其他方法来获取字符串,但我注意到了吗?getActivity().getBaseContext().getString工作,而getActivity().getString不是工作。即使以下代码也不起作用,并且始终app_name在默认资源string.xml中显示vlaue。
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"/>
Run Code Online (Sandbox Code Playgroud)
我在https://github.com/Freydoonk/LanguageTest中共享示例代码
也getActivity()..getResources().getIdentifier行不通,总是返回0!
我有一个多语言的应用程序与主要语言英语和第二语言阿拉伯语.
我打电话setLocale()的onCreate()每一个Activity在我的应用程序:
public static void setLocale(Locale locale){
Locale.setDefault(locale);
Context context = MyApplication.getInstance();
final Resources resources = context.getResources();
final Configuration config = resources.getConfiguration();
config.setLocale(locale);
context.getResources().updateConfiguration(config,
resources.getDisplayMetrics());
}
Run Code Online (Sandbox Code Playgroud)
其中locale一个是以下之一:
在调用之前 super.onCreate(savedInstanceState)调用上述方法.
如文档中所述,
android:supportsRtl="true"在清单中添加了.left和right属性start,并end分别.res\values-ar\strings文件夹中,并将可绘制资源放在res\drawable-ar文件夹中(对于其他资源也是如此).以上设置正常.改变后的Locale到ar-AE,阿拉伯文字和资源都正确地显示在我的活动.
但是,对于版本8.0及更高版本的所有Android设备,资源和布局方向都存在问题.
在版本低于8.0的设备上,RTL屏幕正确如下所示:
在所有8.0+的设备上,同样的屏幕看起来像这样:
这是错的.
事实证明,方向和资源都显示不正确.
这里有两个问题:
Locale在应用配置中似乎没有更新正确的内容. …我正在尝试在我的应用中使用阿拉伯语和英语.它在牛轧糖或以下运行的设备上运行良好.但它不适用于奥利奥设备.API 26中是否有一些新的代码要求?我正在使用下面的代码.
public void changeLanguage(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = context.getResources().getConfiguration();
config.setLocale(locale);
context.createConfigurationContext(config);
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
Run Code Online (Sandbox Code Playgroud)
而我正在传递"en"和"ar"作为语言论证.