Search code examples
androidandroid-fragmentsandroid-activitylocaleandroid-resources

How can I change language programmatically for fragments?


I change locale this way.

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

It's perfect works for activities but doesn't work for fragments.


Solution

  • You need to refresh the fragment after setting the locale. The language won't change if you don't recreate an Activity, similarly, refresh a Fragment like this:

    Fragment frag = null;
    frag = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
    final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.detach(frag);
    fragmentTransaction.attach(frag);
    fragmentTransaction.commit();
    

    If there's no tag in your fragment, add the following code:

    fragmentManager.beginTransaction().replace(R.id.your_id, fragment, "Your_Fragment_TAG").commitAllowingStateLoss();