DataBinding:如何通过动态 id 获取资源? [英] DataBinding: How to get resource by dynamic id?
问题描述
我知道可以通过资源 ID 引用布局中的资源:
I know that it is possible to reference resources in layout by their resource id:
android:text="@{@string/resourceName}"
但是,我想通过仅在运行时已知的 id 来引用资源.作为一个简单的例子,假设我们有这样的模型:
However, I would like to reference resource by id which is known only at runtime. As a simple example, imagine we have such model:
public class MyPOJO {
public final int resourceId = R.string.helloWorld;
}
现在我需要将此值用作格式字符串中的值.让我们称之为
And now I need to use this value as a value in a format string. Let's call it
<string name="myFormatString">Value is: %s</string>
最直接的方法不起作用:
The most straightforward approach does not work:
android:text="@{@string/myFormatString(myPojo.resourceId)}"
这只会将整数值放入占位符(这也证明我正确初始化了我的 POJO,所以我没有在这里提供整个布局).
This will just put integer value into placeholder (also it proves that I initialized my POJO correctly, so I'm not providing whole layout here).
我也尝试过使用 @BindingConversion
,但它没有奏效(这实际上是预期的,但我还是尝试了) - int
仍然被分配给占位符和绑定方法没有被调用.
I also tried using @BindingConversion
, but it did not worked (which is actually expected, but I tried anyway) - int
was still assigned to placeholder and binding method was not called.
如何通过 DataBinding 库中的 id 显式获取资源?
How can I explicitly get resource by it's id in DataBinding library?
推荐答案
我最终创建了自己的方法:
I ended up creating my own method:
public class BindingUtils {
public static String string(int resourceId) {
return MyApplication
.getApplication()
.getResources()
.getString(resourceId);
}
}
为其声明导入:
<data>
<import type="com.example.BindingUtils" />
...
</data>
并且只是在绑定期间调用它:
And just calling it during binding:
android:text="@{@string/myFormatString(BindingUtils.string(myPojo.resourceId))}"
如果有开箱即用的方法就好了.DataBinding 还处于 Beta 阶段 - 所以也许将来会出现.
Would be nice to have out-of-the-box method for that. DataBinding is sitll in Beta - so maybe it will come in future.
这篇关于DataBinding:如何通过动态 id 获取资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!