我可以从不同的locale android访问资源吗?

vik*_*for 10 android locale

我的应用程序中有两个区域设置.我是否可以访问资源,例如来自不同语言环境的字符串数组,而无需更改当前语言环境?我的意思是编码我不喜欢在设置中更改它.

Eug*_*nov 24

更好的解决方案是(如果您使用的是API 17):

@NonNull
protected String getEnglishString() {
    Configuration configuration = getEnglishConfiguration();

    return getContext().createConfigurationContext(configuration).getResources().getString(message);
}

@NonNull
private Configuration getEnglishConfiguration() {
    Configuration configuration = new Configuration(getContext().getResources().getConfiguration());
    configuration.setLocale(new Locale("en"));
    return configuration;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这也是Google推荐的解决方案:https://code.google.com/p/android/issues/detail?id=67672 (2认同)

vik*_*for 9

如果cMK是来自当前语言环境的String数组,而cEN是来自不同语言环境的字符串数组,那么这个代码对我有用.

 cMK = getResources().getStringArray(R.array.cities);

         Configuration confTmp =new Configuration( getResources().getConfiguration());

         confTmp.locale = new Locale("en");

         DisplayMetrics metrics = new DisplayMetrics();

         getWindowManager().getDefaultDisplay().getMetrics(metrics);

         Resources resources = new Resources(getAssets(), metrics, confTmp);

         /* get localized string */
         cENG = getResources().getStringArray(R.array.cities);
Run Code Online (Sandbox Code Playgroud)

当前的语言环境没有改变,这就是重点.

  • 你的意思是:"cENG = resources.getStringArray(R.array.cities);" ? (6认同)
  • 它会更改上下文的区域设置(例如,针对您的活动) (2认同)