DataBinding:如何通过动态ID获取资源? [英] DataBinding: How to get resource by dynamic id?

查看:613
本文介绍了DataBinding:如何通过动态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>

最简单的方法行不通:

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))}"

为此提供开箱即用的方法将是很好的. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆