是否可以在使用Android资源的同时以编程方式更改应用程序的语言?
如果没有,是否可以请求特定语言的资源?
我想让用户从应用程序更改应用程序的语言.
就在最近的context.getResources().updateConfiguration()已在Android API 25中弃用,建议使用上下文.而是createConfigurationContext().
有谁知道createConfigurationContext如何用于覆盖android系统区域设置?
在此之前将通过以下方式完成:
Configuration config = getBaseContext().getResources().getConfiguration();
config.setLocale(locale);
context.getResources().updateConfiguration(config,
context.getResources().getDisplayMetrics());
Run Code Online (Sandbox Code Playgroud) 我有一个支持多种语言的旧项目。我想升级支持库和目标平台,在迁移到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!
我正在使用AddressLine当地语言(印地语).
我正在使用Locale.getDefault(),认为这可能是原因.
但即使改变它后Locale.ENGLISH我也得到了相同的结果.
List<Address> addresses = null;
try {
Geocoder gCoder = new Geocoder(c, Locale.ENGLISH);
addresses = gCoder.getFromLocation(lat, lng, 1);
Address addr = addresses.get(0);
String addressLine = addr.getAddressLine(0);
}catch{
}
Run Code Online (Sandbox Code Playgroud)
我希望它能用英语给出值,如果不可能的话,返回null,这样我就可以使用除AddressLine以外的其他东西了.
编辑:
试过这个
Locale mLocale = new Locale("en");
Log.d("Display language = ", "" + mLocale.getDisplayLanguage());
Geocoder gCoder = new Geocoder(c, mLocale);
LogCat: Display language = English
Run Code Online (Sandbox Code Playgroud)
但我得到了相同的结果.
谢谢