如何在android中获取默认字符串值?

时间:2012-12-11 15:31:08

标签: android localizable.strings

我已在我的Android应用程序中实现了本地化,但我遇到了一个小问题。 我无法从默认strings.xml文件中检索字符串的默认值。 例如。 在project/res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
        <string name="distance">distance</string>
</resources>

project/res/values-nl/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <string name="distance">afstand</string>
</resources>

我的要求是从project / res / values / strings.xml文件中获取'distance'变量的值,而不管当前使用的是哪个语言环境。

1 个答案:

答案 0 :(得分:0)

我们可以使用上下文配置来完成它,它可以在API +17中运行,如:

public static String getDefaultString(Context context, @StringRes int stringId){
        Resources resources = context.getResources();
        Configuration configuration = new Configuration(resources.getConfiguration());
        Locale defaultLocale = new Locale("en"); // default locale
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleList localeList = new LocaleList(defaultLocale);
            configuration.setLocales(localeList);
            return context.createConfigurationContext(configuration).getString(stringId);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
            configuration.setLocale(defaultLocale);
            return context.createConfigurationContext(configuration).getString(stringId);
        }
        return context.getString(stringId);
    }

对于早期版本的Android,您可以使用类似的内容:

public static String getDefaultString(Context context, @StringRes int stringId){
  Resources resources = context.getResources();
  Locale defaultLocale = new Locale("en");// default locale
  configuration.locale = newLocale;
  resources.updateConfiguration(configuration, res.getDisplayMetrics());
  return resources.getString();
}

但我想它可以改变应用程序中的当前上下文。如果您不在应用中使用默认语言,则本地化会出现问题。

相关问题