如何以编程方式更改片段的语言?

时间:2019-08-26 18:26:40

标签: android android-fragments android-activity locale android-resources

我以此方式更改语言环境。

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)
}

对于活动而言,它是完美的选择,但对于片段而言,则不适用。

1 个答案:

答案 0 :(得分:0)

设置区域设置后,您需要刷新片段。如果您不重新创建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();