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

后端 未结 1 951
梦谈多话
梦谈多话 2021-01-02 21:08

I have an Activity say ActivityMain from this activity I moved to another activity called ActivitySettings and in settings activity I\'m changing t

相关标签:
1条回答
  • 2021-01-02 21:37

    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();
        }
        ...
    }
    
    0 讨论(0)
提交回复
热议问题