如何以编程方式更改片段的语言?
How can I change language programmatically for fragments?
我用这种方式更改语言环境。
override fun attachBaseContext(base: Context) {
super.attachBaseContext(updateResources(base, sessionInteractor.locale))
}
fun updateResources(context: Context, locale: Locale): Context {
Locale.setDefault(locale)
val resources = context.resources
val config = Configuration(resources.configuration)
config.setLocale(locale)
return context.createConfigurationContext(config)
}
它非常适合活动,但不适用于片段。
您需要在设置语言环境后刷新片段。如果您不重新创建 Activity
,语言将不会改变,类似地,像这样刷新 Fragment
:
Fragment frag = null;
frag = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.detach(frag);
fragmentTransaction.attach(frag);
fragmentTransaction.commit();
如果您的片段中没有标签,请添加以下代码:
fragmentManager.beginTransaction().replace(R.id.your_id, fragment, "Your_Fragment_TAG").commitAllowingStateLoss();
我用这种方式更改语言环境。
override fun attachBaseContext(base: Context) {
super.attachBaseContext(updateResources(base, sessionInteractor.locale))
}
fun updateResources(context: Context, locale: Locale): Context {
Locale.setDefault(locale)
val resources = context.resources
val config = Configuration(resources.configuration)
config.setLocale(locale)
return context.createConfigurationContext(config)
}
它非常适合活动,但不适用于片段。
您需要在设置语言环境后刷新片段。如果您不重新创建 Activity
,语言将不会改变,类似地,像这样刷新 Fragment
:
Fragment frag = null;
frag = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.detach(frag);
fragmentTransaction.attach(frag);
fragmentTransaction.commit();
如果您的片段中没有标签,请添加以下代码:
fragmentManager.beginTransaction().replace(R.id.your_id, fragment, "Your_Fragment_TAG").commitAllowingStateLoss();