Android activity that uses a custom locale for its duration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LocaleSwitchActivity extends Activity { | |
private static final String LOG_TAG = LocaleSwitchActivity.class.getSimpleName(); | |
private static final String LOCALE_EXTRA = "locale"; | |
private Locale customLocale; | |
private boolean restartingForLocaleChangeFlag; | |
protected void useLocale(Locale locale) { | |
Intent intent = getIntent(); | |
if (locale == null) { | |
Locale def = Locale.getDefault(); | |
Log.i(LOG_TAG + ".useLocale", "restarting the activity" + | |
" in the default locale " + def); | |
intent.putExtra(LOCALE_EXTRA, def); | |
} else { | |
Log.i(LOG_TAG + ".useLocale", "restarting the activity in" + | |
" the " + locale + " locale"); | |
intent.putExtra(LOCALE_EXTRA, locale); | |
} | |
restartingForLocaleChangeFlag = true; | |
overridePendingTransition(0, 0); | |
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); | |
finish(); | |
overridePendingTransition(0, 0); | |
startActivity(intent); | |
} | |
private void simpleSetLocale(Configuration config, Locale loc) { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { | |
config.setLocale(loc); | |
} else { | |
config.locale = loc; | |
} | |
} | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
Intent intent = getIntent(); | |
if (intent.hasExtra(LOCALE_EXTRA)) { | |
Object extra = intent.getSerializableExtra(LOCALE_EXTRA); | |
if (extra != null && extra instanceof Locale) { | |
customLocale = (Locale) extra; | |
Resources res = getResources(); | |
Configuration config = res.getConfiguration(); | |
simpleSetLocale(customLocale); | |
res.updateConfiguration(config, res.getDisplayMetrics()); | |
} | |
} | |
} | |
@Override | |
public void onStop() { | |
super.onStop(); | |
// reset locale | |
if (customLocale != null && !restartingForLocaleChangeFlag) { | |
customLocale = null; | |
Locale defaultLocale = Locale.getDefault(); | |
Log.i(LOG_TAG + ".useLocale", "reverting the locale to" + | |
" the default " + defaultLocale); | |
Resources res = getResources(); | |
Configuration config = res.getConfiguration(); | |
simpleSetLocale(config, defaultLocale); | |
res.updateConfiguration(config, res.getDisplayMetrics()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment