是否有可能在使用Android资源的同时以编程方式改变应用程序的语言?
如果不是,是否可以用特定的语言请求资源?
我想让用户改变应用程序的语言从应用程序。
是否有可能在使用Android资源的同时以编程方式改变应用程序的语言?
如果不是,是否可以用特定的语言请求资源?
我想让用户改变应用程序的语言从应用程序。
当前回答
Resources.updateConfiguration()已经弃用,我已经解决了这个问题,没有创建任何自定义的ContextWrapper。
首先我创建了一个扩展函数
fun Context.setAppLocale(language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val config = resources.configuration
config.setLocale(locale)
config.setLayoutDirection(locale)
return createConfigurationContext(config)
}
然后在活动的attachBaseContext方法中,简单地用新的上下文替换上下文。
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(ContextWrapper(newBase.setAppLocale("bn")))
}
其他回答
这是工作时,我按下按钮改变我的TextView的文本语言。(strings.xml在值-de文件夹)
String languageToLoad = "de"; // your language
Configuration config = getBaseContext().getResources().getConfiguration();
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
recreate();
androidx。Appcompat: Appcompat用户,以上解决方案将在1.3.0版本后工作。 就像这里提到的。
我正在寻找一种以编程方式改变系统语言的方法。 虽然我完全理解一个正常的应用程序不应该这样做,而是:
用户应该(通过一个意图)指向系统设置手动更改它 应用程序应该自己处理本地化,就像Alex的回答中描述的那样
有必要从程序上真正改变系统的语言。
这是没有文档的API,因此不应该用于市场/最终用户应用程序!
不管怎样,这是我找到的解决方案:
Locale locale = new Locale(targetLocaleAsString);
Class amnClass = Class.forName("android.app.ActivityManagerNative");
Object amn = null;
Configuration config = null;
// amn = ActivityManagerNative.getDefault();
Method methodGetDefault = amnClass.getMethod("getDefault");
methodGetDefault.setAccessible(true);
amn = methodGetDefault.invoke(amnClass);
// config = amn.getConfiguration();
Method methodGetConfiguration = amnClass.getMethod("getConfiguration");
methodGetConfiguration.setAccessible(true);
config = (Configuration) methodGetConfiguration.invoke(amn);
// config.userSetLocale = true;
Class configClass = config.getClass();
Field f = configClass.getField("userSetLocale");
f.setBoolean(config, true);
// set the locale to the new value
config.locale = locale;
// amn.updateConfiguration(config);
Method methodUpdateConfiguration = amnClass.getMethod("updateConfiguration", Configuration.class);
methodUpdateConfiguration.setAccessible(true);
methodUpdateConfiguration.invoke(amn, config);
如果你写
android:configChanges="locale"
在每个活动中(在清单文件中),那么不需要每次输入activity时都设置它。
对于Android 7.0牛轧糖(或更低),请遵循这篇文章:
在Android中以编程方式改变语言
旧的答案 这包括RTL/LTR支持:
public static void changeLocale(Context context, Locale locale) {
Configuration conf = context.getResources().getConfiguration();
conf.locale = locale;
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLayoutDirection(conf.locale);
}
context.getResources().updateConfiguration(conf, context.getResources().getDisplayMetrics());
}