How to change Android O / Oreo / api 26 app language

前端 未结 8 1481
深忆病人
深忆病人 2020-12-01 04:37

I want to change the language of the app and this works fine until API 26.

For api > 25 I put Locale.setDefault(Locale.Category.DISPLAY, mynewlanglocale);

8条回答
  •  情歌与酒
    2020-12-01 05:18

    Here is complete solution worked for kitkat, Lollipop, Marshmallow, Nougat and Oreo too. Just follow all below step.

    First create a java class like below

    import android.content.Context;
    import android.content.res.Configuration;
    import java.util.Locale;
    public class LocaleUtils {
    public static void updateConfig(Context mContext, String sLocale) {
        Locale locale = new Locale(sLocale);
        Locale.setDefault(locale);
        Configuration config = mContext.getResources().getConfiguration();
        config.locale = locale;
        mContext.getResources().updateConfiguration(config,
                mContext.getResources().getDisplayMetrics());
      }
    }
    

    Now add this snippet on Button click where you want to change locale

    String lang="hi";//pass your language here
    SharedPreferences preferences =  PreferenceManager.getDefaultSharedPreferences(mContext);
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.clear();
                            editor.putString("lang", lang");
                            editor.putBoolean("langSelected", true);
                            editor.apply();
                            LocaleUtils.updateConfig(mContext,lang);
                            Intent intent = mContext.getIntent();
                            mContext.overridePendingTransition(0, 0);
                            mContext.finish();
                            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            mContext.overridePendingTransition(0, 0);
                            mContext.startActivity(intent);
    

    Finally paste the below code in Splash Activity or in Launching Activity.

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String lang = preferences.getString("lang", "");
        boolean langSelected = preferences.getBoolean("langSelected", false);
        SharedPreferences.Editor editor = preferences.edit();
        if (langSelected) {
            editor.clear();
            editor.putString("lang", lang);
            editor.putBoolean("langSelected", true);
            editor.apply();
            LocaleUtils.updateConfig(this,lang);
        } else {
            LocaleUtils.updateConfig(this, Locale.getDefault().getLanguage());
            editor.clear();
            editor.putString("lang", Locale.getDefault().getLanguage());
            editor.putBoolean("langSelected", false);
            editor.apply();
        }
    

提交回复
热议问题