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

葡萄

我以这种方式更改语言环境。

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

它非常适合活动,但不适用于片段。

萨阿德·阿卡什(SaadAAkash)

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章