gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:14:30 25 4
gpt4 key购买 nike

我已经在我的 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”变量的值,而不管当前使用的是哪个语言环境。

最佳答案

我们可以使用上下文配置来完成它,它将在 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();
}

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

关于android - 如何在android中获取默认字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13823093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com