2017年2月12日 星期日

How to set language in Android

use the below class

public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static void onCreate(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        setLocale(context, lang);
    }

    public static void onCreate(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static void setLocale(Context context, String language) {
        persist(context, language);
        updateResources(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    private static void updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    }
}



How to use?


In Application

  public void onCreate() {
        super.onCreate();
        LocaleHelper.onCreate(this, "en");

 @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        LocaleHelper.setLocale(this, LocaleHelper.getLanguage(this));
    }


Set the language

LocaleHelper.setLocale(this, "en");

How to change the language without restart the activity

LocaleHelper.setLocale(this, "zh");


set the text that you can see
e.g.
tvEn.setText(getContext().getString(R.string.en));
        tvTc.setText(getContext().getString(R.string.tc));
        tvChangePsw.setText(getContext().getString(R.string.change_psw));
        tvChangeLang.setText(getContext().getString(R.string.change_lang));
        tvPushNote.setText(getContext().getString(R.string.push_notic));
        tvPromotion.setText(getContext().getString(R.string.promotion));
        tvHealthTips.setText(getContext().getString(R.string.health_tips));
        tvLogout.setText(getContext().getString(R.string.logout));