【问题标题】:How to get default string value in android?如何在android中获取默认字符串值?
【发布时间】:2012-12-11 15:31:08
【问题描述】:

我已经在我的 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 文件中获取“距离”变量的值,无论当前使用的是哪个语言环境。

【问题讨论】:

  • 你的问题到底是什么?
  • getApplicationContext().getString(R.string.distance) 在使用英语语言环境时将值检索为“距离”,在使用荷兰语语言环境时检索值为“afstand”。但无论当前使用的语言环境如何,我都希望将值设为“距离”。
  • 那么在荷兰语环境中不要将其提及为 afstand 而将其提及为距离
  • 不,我不能那样做。我也需要它用于其他目的。还是谢谢你

标签: android localizable.strings


【解决方案1】:

我们可以通过上下文配置来做到这一点,它可以在 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();
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    相关资源
    最近更新 更多