Created
November 3, 2020 22:29
-
-
Save TechIsFun/e18ba6e9b6fc2eaf0881bf0972552ebb to your computer and use it in GitHub Desktop.
A test rule for setting device locale
This file contains hidden or 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 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