pau-riquelme

Untitled

Dec 29th, 2017
620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. public class LocaleRule implements TestRule {
  2.  
  3.    private final Locale[] mLocales;
  4.    private Locale mDeviceLocale;
  5.  
  6.    public LocaleRule(Locale... locales) {
  7.        mLocales = locales;
  8.    }
  9.  
  10.    @Override
  11.    public Statement apply(final Statement base, Description description) {
  12.        return new Statement() {
  13.            @Override
  14.            public void evaluate() throws Throwable {
  15.                try {
  16.                    if (mLocales != null) {
  17.                        mDeviceLocale = Locale.getDefault();
  18.  
  19.                        for (Locale locale : mLocales) {
  20.                            setLocale(locale);
  21.                            base.evaluate();
  22.                        }
  23.                    }
  24.                } finally {
  25.                    if (mDeviceLocale != null) {
  26.                        setLocale(mDeviceLocale);
  27.                    }
  28.                }
  29.            }
  30.        };
  31.    }
  32.  
  33.    private void setLocale(Locale locale) {
  34.        Resources resources = InstrumentationRegistry
  35.             .getTargetContext()
  36.             .getResources();
  37.  
  38.        Locale.setDefault(locale);
  39.        Configuration config = resources.getConfiguration();
  40.        config.setLocale(locale);
  41.        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
  42.        resources.updateConfiguration(config, displayMetrics);
  43.    }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment