Search code examples
androidbackonresume

Android - Language change when clicking back


I have this settings section where I allow users to change the languages displayed within the app. When the user chooses a different language, the activity is reloaded so that the change of language can be applied. But the problem is, when the user clicks back right after changing the language, the language shown in the background activity is still the same. So my question is, what should I do to apply the change of language when I get back to some activity on the background? I suppose I should do something to detect the change in onResume method, but I'm not sure what it is. If you have any suggestions, please let me know. Thank you.


Solution

  • After several attempts, I have found the solution to my problem. On my onCreate method, I get the SharedPreferences that contains the value of current language, and get the current language:

    SharedPrefrences languagepref = getSharedPreferences("language",MODE_PRIVATE);
    String language = languagepref.getString("languageToLoad", Locale.getDefault().getDisplayLanguage());
    

    Then, in my onResume method, I assign the value of the above mentioned variable language to a local variable, and update the value of language. Then I compare these two variables - if they are different, I will destroy the current activity and start another:

    @Override
        public void onResume(){
            super.onResume();       
    
            String oldLanguage = language;
            language = languagepref.getString("languageToLoad", Locale.getDefault().getDisplayLanguage());
            if (!oldLanguage.equals(language)){
                finish();
                startActivity(getIntent());
            }
        }
    

    And voila, that did the trick!