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

xj3cbfub  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(252)

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

  1. <string-array name="distance_rating_labels">
  2. <item>&lt; 5 %s</item>
  3. <item>&lt; 10 %s</item>
  4. <item>&lt; 15 %s</item>
  5. </string-array>

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

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


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

yshpjwxd

yshpjwxd1#

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

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

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

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

展开查看全部

相关问题