5

Not Able to change locale without recreating Activity
An application has support of two languages, when i change the language then i must have to recreate the activity to show to desired result but i don't want to do it.

private void setNewLocale(AppCompatActivity mContext, @LocaleManager.LocaleDef String language) {
        LocaleManager.setNewLocale(this, language);
        Intent intent = mContext.getIntent();
        startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
    }

Also i set the text again on All textfield but it didn't help!

When i am on the third activity of app and i change the language when i get back to second activity the text on second and first activity if i want to then i have to recreate those activity as well which i think is bad approach to do it. I only want to change language but didn't want to recreate the activity!

On Button Click, i set the Locale!

if(appPreference.getLanguage().equalsIgnoreCase("en")){
   setNewLocale(MainActivity.this, LocaleManager.ARABIC);
}
else
    setNewLocale(MainActivity.this, LocaleManager.ENGLISH);
Ahmad Idrees
  • 181
  • 3
  • 12

1 Answers1

1

First Define these function in your Activity

public void setLocale(String lang) {

        Locale 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);
    }

    private static void setLanguagePref(Context mContext, String localeKey) {
        AppPreference appPreference = new AppPreference(mContext);
        appPreference.setLanguage(localeKey);
    }

    public static String getLanguagePref(Context mContext) {
        AppPreference appPreference = new AppPreference(mContext);
        return appPreference.getLanguage();
    }

Override these functions

@Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        //set Text Again of All layouts
        //Prefer to make a function and then set All Text

        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onResume() {

        setLocale(getLanguagePref(getApplicationContext()));
        super.onResume();
    }

Now set the Language on Any Event like Onclick

   setLocale("ar");
   setLanguagePref(MainActivity.this, "ar");
Ahmad Idrees
  • 181
  • 3
  • 12