Refresh(recreate) the activities in back stack when change locale at run time

前提是你 提交于 2019-11-30 18:34:14

问题


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 button, and using recreate I achieved the change I need in current activity but when I press back my `ActivityMain' will resume but locale is not updated.

Can some one tell me how to 'Recreate' backstack activities? what will be the correct approach.

I can't call recreate on refresh as it will be infinite loop


回答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:

public class ActivityA extends AppCompatActivity{
    private String currentLangCode;
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        currentLangCode = getResources().getConfiguration().locale.getLanguage();
        ...
    }
    @Override
    public void onResume(){
        ...
        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:

public class BaseActivity extends AppCompatActivity{
    private String currentLangCode;
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        currentLangCode = getResources().getConfiguration().locale.getLanguage();
        ...
    }
    @Override
    public void onResume(){
        ...
        if(!currentLangCode.equals(getResources().getConfiguration().locale.getLanguage();)){
            currentLangCode = getResources().getConfiguration().locale.getLanguage();
            recreate();
        }
    }
    ...
}

Extend all Activities from BaseActivity

public class ActivityA extends BaseActivity{

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }
    @Override
    public void onResume(){
      super.onResume();
    }
    ...
}


来源:https://stackoverflow.com/questions/51097334/refreshrecreate-the-activities-in-back-stack-when-change-locale-at-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!