以编程方式调用通用字符串资源

Call generic string resource programmatically

strings.xml 我有一个资源。

<string name="generic_price_with_rupee_symbol">\u20B9 %s</string>

这就是我在 Android 数据绑定 中所做的,效果很好

<TextView
      ...
      android:text="@{@string/generic_price_with_rupee_symbol(item.price)}"
      />

问题:

如何在java代码中使用这个资源?因为我不想制作新资源。

我试过了

textView.setText(getString(R.string.generic_price_with_rupee_symbol) + "100");

这给出了错误的结果并打印了 %s

应该这样写 -

textView.setText(getString(R.string.generic_price_with_rupee_symbol, "100"));

查看 String getString (int resId, 对象... formatArgs) 来自文档。

格式化值应作为参数作为第二个值传递给 getString(int, Object..) 方法

其中 Object...

The format arguments that will be used for substitution

所以使用

textView.setText(getString(R.string.generic_price_with_rupee_symbol, "100"));
//                                                                  ^^^

使用以下内容:-

textView.setText(getResources().getString(R.string.generic_price_with_rupee_symbol, "100"));