Search code examples
androidsharedpreferenceslocaleonconfigurationchanged

Why does android:label's text not changing when user changes language within my app?


So within my app, the very first Activity that user sees is to choose language.

Lets say if user chooses french and then goes to ActivityB, then to ActivityC.

Now decides to changes language.

So goes back to ActivityB and then to very first Activity and choses language as Spanish.

Now again when user goes to ActivityB, all other text within the fragment/activity is changed to Spanish, but android:label still remains in French. how to fix this?

This is how my ActivityA looks

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             final Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_choose_language, container, false);
        radioGroup = (RadioGroup) rootView.findViewById(R.id.lang_choice_radio);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.english_lang:
                        // do operations specific to this selection
                        setLocale("en_US");
                        Intent intentEng = new Intent(getActivity(), Choose_Country.class);
                        startActivity(intentEng);
                        break;

                    case R.id.indonesian_lang:
                        // do operations specific to this selection
                        setLocale("in");
                        Intent intent = new Intent(getActivity(), Choose_Country.class);
                        startActivity(intent);
                        break;
                }
            }
        });
        return rootView;
    }

    public void setLocale(String lang) {
        myLocale = new Locale(lang);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
        Locale.setDefault(myLocale);
        onConfigurationChanged(conf);
        Intent refreshIntent = new Intent(getActivity(), ChooseLanguage.class); // refresh the activity
        refreshIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        refreshIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(refreshIntent);
        getActivity().finish();
    }

Solution

  • In my case, app won't change Actionbar language after change locale. It will change when I remove app from the recent app which make the app completely close. To solve, I use setTitle(R.id.myapplabel) when you want to refresh app or oncreate, so no need to restart app. Translate your activity label on string.xml and it should works.