android strings.xml中字符串数组中的占位符

xj3cbfub  于 5个月前  发布在  Android
关注(0)|答案(1)|浏览(82)

我试图在字符串数组中使用占位符(每个项目都将使用相同的值)。

<string-array name="distance_rating_labels">
    <item>&lt; 5 %s</item>
    <item>&lt; 10 %s</item>
    <item>&lt; 15 %s</item>
</string-array>

字符串
这里我想根据运行时传递的距离度量返回< 5 km< 5 miles

<string name="less_than_5">&lt; 5 %s</string>


但是有没有可能用数组来做呢?任何帮助都将不胜感激。

yshpjwxd

yshpjwxd1#

Resources.getString(id, formatArgs)的源代码(Context.getString(id, formatArgs)的方法)如下所示:

@NonNull
public String getString(@StringRes int id, Object... formatArgs) throws NotFoundException {
    final String raw = getString(id);
    return String.format(mResourcesImpl.getConfiguration().getLocales().get(0), raw,
            formatArgs);
}

字符串
因此,你可以这样做:

val resources = context.resources
val rawLabels = resources.getStringArray(R.array.distance_rating_labels)
val currentLocale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
    resources.configuration.locales.get(0)
else
    resources.configuration.locale
val distance = String.format(currentLocale, rawLabels[index], arg)

相关问题