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

3

我已在我的Android应用程序中实现了本地化,但是我有一个小问题。 我无法从默认字符串.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>

我的需求是从项目/res/values/strings.xml文件中获取'distance'变量的值,无论当前使用哪种语言环境。


你的问题到底是什么? - G_S
getApplicationContext().getString(R.string.distance) 在使用英语语言环境时返回值为“distance”,在使用荷兰语语言环境时返回值为“afstand”。但是,我希望无论当前使用的语言环境是什么,都能够获得“distance”这个值。 - Dipendra
那么在荷兰语环境中,不要将其称为“afstand”,而应该称之为“distance”。 - G_S
抱歉,我不能这样做。我也需要它做其他用途。不管怎样,谢谢您。 - Dipendra
@Dipendra - 你可以试试这个链接:http://stackoverflow.com/questions/14984659/android-strings-xml-in-various-languages-scenario - Braj
1个回答

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();
}

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接