import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.preference.PreferenceManager;
import java.util.Locale;
public class LocaleHelper {
private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
}
public static Context setNewLocale(Context mContext, String language) {
persist(mContext, language);
return updateLocale(mContext, getLanguage(mContext));
}
public static Context setLocale(Context context) {
persist(context, getLanguage(context));
return updateLocale(context, getLanguage(context));
}
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 Context updateLocale(Context context, String lang) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
Locale localeToSwitchTo = new Locale(lang);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
configuration.setLocale(localeToSwitchTo);
LocaleList localeList = new LocaleList(localeToSwitchTo);
LocaleList.setDefault(localeList);
configuration.setLocales(localeList);
context = context.createConfigurationContext(configuration);
} else {
Locale.setDefault(localeToSwitchTo);
configuration.locale = localeToSwitchTo;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
}
return context;
}
}
//Activity class
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.setLocale(base));
}
private void setNewLocale(Context mContext, String language) {
try {
LocaleHelper.setNewLocale(this, language);recreate();//recreate activity
} catch (Exception e) {
e.printStackTrace();
FirebaseCrashlytics.getInstance().recordException(e);
}
}