Skip to content Skip to sidebar Skip to footer

Refresh(recreate) The Activities In Back Stack When Change Locale At Run Time

I have an Activity say ActivityMain from this activity I moved to another activity called ActivitySettings and in settings activity I'm changing the App locale by clicking on a but

Solution 1:

In each Activity's onCreate() you can maintain the currentLangCode. Check this value in onResume(), if it differs, you can conclude the locale was change and recreate()

You can do it as follows:

publicclassActivityAextendsAppCompatActivity{
    privateString currentLangCode;
     @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        ...
        currentLangCode = getResources().getConfiguration().locale.getLanguage();
        ...
    }
    @OverridepublicvoidonResume(){
        ...
        if(!currentLangCode.equals(getResources().getConfiguration().locale.getLanguage())){
            currentLangCode = getResources().getConfiguration().locale.getLanguage();
            recreate();
        }
    }
    ...
}

My Recommendation

If you want to apply it for all the Activities, then simply create BaseActivity as follows:

publicclassBaseActivityextendsAppCompatActivity{
    privateString currentLangCode;
     @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        ...
        currentLangCode = getResources().getConfiguration().locale.getLanguage();
        ...
    }
    @OverridepublicvoidonResume(){
        ...
        if(!currentLangCode.equals(getResources().getConfiguration().locale.getLanguage();)){
            currentLangCode = getResources().getConfiguration().locale.getLanguage();
            recreate();
        }
    }
    ...
}

Extend all Activities from BaseActivity

publicclassActivityAextendsBaseActivity{

     @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }
    @OverridepublicvoidonResume(){
      super.onResume();
    }
    ...
}

Post a Comment for "Refresh(recreate) The Activities In Back Stack When Change Locale At Run Time"