package com.mobapphome.mahads.sample; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.preference.PreferenceManager; import android.util.Log; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancar on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "MAHAds.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) { Log.i(MainActivity.LOG_TAG_MAH_ADS_SAMPLE, "Language = " + 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()); } } // //This for tip // //This for refreshing strings when lacale has changed. // //Write this kind of method to activity or fragment // private void updateViews() { // // if you want you just call activity to restart itself to redraw all the widgets with the correct locale // // however, it will cause a bad look and feel for your users // // // // this.recreate(); // // //or you can just update the visible text on your current layout // Resources resources = getResources(); // // mTitleTextView.setText(resources.getString(R.string.title_text)); // mDescTextView.setText(resources.getString(R.string.desc_text)); // mAboutTextView.setText(resources.getString(R.string.about_text)); // }