Skip to content

Instantly share code, notes, and snippets.

@TechIsFun
Created November 3, 2020 22:29
Show Gist options
  • Save TechIsFun/e18ba6e9b6fc2eaf0881bf0972552ebb to your computer and use it in GitHub Desktop.
Save TechIsFun/e18ba6e9b6fc2eaf0881bf0972552ebb to your computer and use it in GitHub Desktop.
A test rule for setting device locale
public class ForceLocaleRule implements TestRule {
private final Locale mTestLocale;
private Locale mDeviceLocale;
public ForceLocaleRule(Locale testLocale) {
mTestLocale = testLocale;
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
public void evaluate() throws Throwable {
try {
if (mTestLocale != null) {
mDeviceLocale = Locale.getDefault();
setLocale(mTestLocale);
}
base.evaluate();
} finally {
if (mDeviceLocale != null) {
setLocale(mDeviceLocale);
}
}
}
};
}
public void setLocale(Locale locale) {
Resources resources = InstrumentationRegistry.getTargetContext().getResources();
Locale.setDefault(locale);
Configuration config = resources.getConfiguration();
config.locale = locale;
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment