我知道可以通过资源id在布局中引用资源:
android:text="@{@string/resourceName}"
但是,我想通过id引用资源,这只在运行时才知道。作为一个简单的例子,假设我们有这样的模型:
public class MyPOJO {
public final int resourceId = R.string.helloWorld;
}
现在我需要使用这个值作为格式字符串中的一个值。就叫它吧
<string name="myFormatString">Value is: %s</string>
最直接的方法不起作用:
android:text="@{@string/myFormatString(myPojo.resourceId)}"
这将只是将整数值放入占位符(也证明我正确地初始化了我的POJO,所以我没有在这里提供整个布局)。
我也尝试过使用@BindingConversion
,但它不起作用(这实际上是意料之中的,但我还是尝试了)-- int
仍然被分配给占位符,并且绑定方法没有被调用。
如何通过DataBinding库中的id显式获取资源?
发布于 2015-08-29 00:16:55
我最终创建了自己的方法:
public class BindingUtils {
public static String string(int resourceId) {
return MyApplication
.getApplication()
.getResources()
.getString(resourceId);
}
}
为它声明一个导入:
<data>
<import type="com.example.BindingUtils" />
...
</data>
并且只是在绑定期间调用它:
android:text="@{@string/myFormatString(BindingUtils.string(myPojo.resourceId))}"
如果能有开箱即用的方法就好了。DataBinding现在还处于测试阶段--所以它可能会在未来出现。
发布于 2015-10-17 00:14:12
另一种解决方案是为它创建一个自定义的@BindingAdapter
。
@BindingAdapter({"format", "argId"})
public static void setFormattedText(TextView textView, String format, int argId){
if(argId == 0) return;
textView.setText(String.format(format, textView.getResources().getString(argId)));
}
然后只需单独提供变量。
<TextView
app:format="@{@string/myFormatString}"
app:argId="@{myPojo.resourceId}"
如果需要多个参数,可以使用数组,但在我的例子中,一个就足够了。
发布于 2016-06-27 16:45:08
从2016年6月起,这在XML中是可能的:
android:text= "@{String.format(@string/my_format_string, myPojo.resourceId)}"
https://stackoverflow.com/questions/32273517
复制相似问题