【发布时间】:2021-09-14 12:46:06
【问题描述】:
我使用下面的代码将语言从默认更改为选中。但是我无法使用所选语言更新我的片段/活动中的视图,例如 TextView。以编程方式显示所选语言。
即使我在 Manifest 文件中声明 android:configChanges="layoutDirection|locale",我的应用程序也是 potrait onConfigurationChanged() 也没有调用
注意:我不想重新创建()我的活动。
1.使用 BaseActivity 为 attachBaseContext 设置语言环境并为所有活动扩展此活动
open class BaseAppCompactActivity() : AppCompatActivity() {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(LocaleHelper.onAttach(newBase))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
}
2.使用Application attachBaseContext 和onConfigurationChanged 设置语言环境。
public class MyApplication extends Application {
private static MyApplication application;
@Override
public void onCreate() {
super.onCreate();
}
public static MyApplication getApplication() {
return application;
}
/**
* overide to change local sothat language can be chnaged from android device nogaut and above
*/
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.INSTANCE.onAttach(base));
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
/*** also handle chnage language if device language chnaged **/
super.onConfigurationChanged(newConfig);
}
3.使用 Locale Helper 处理语言变化,此方法适用于所有设备
object LocaleHelper {
fun onAttach(context: Context, defaultLanguage: String): Context {
return setLocale(context, defaultLanguage)
}
fun setLocale(context: Context, language: String): Context {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResources(context, language)
} else updateResourcesLegacy(context, language)
}
@TargetApi(Build.VERSION_CODES.N)
private fun updateResources(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val configuration = context.getResources().getConfiguration()
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
return context.createConfigurationContext(configuration)
}
private fun updateResourcesLegacy(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.getResources()
}
【问题讨论】:
-
看看这个资源:proandroiddev.com/…。长话短说,这个博客包含你所有的疑问,简而言之,请选择第 3 方库或从库中获取部分代码(在那篇文章中提到)处理 API 级别的 25+ 变化,这些变化 android 生态系统已经做了很多.
-
嘿@Zaraki596 我尝试使用 getResources() 获取文本,但在重新创建活动之前它不会更新视图。我的情况我不想重新创建它。
标签: android kotlin resources locale recreate