1

我开始使用新的数据绑定 API。我想绑定TextView一个自定义属性,我可以在其中一次更改文本和背景。据我了解,api 有一个@BindingMethod注释,但文档有点弱。

我想要这样的东西:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="Important"
    tools:background="@drawable/bg_badge_important"
    tools:textColor="#fff"
    android:id="@+id/badge"
    custom:badge="@{item.badge}"/>

item.badge是一个字符串,如重要或通知。对于 i18n,我不能直接使用此字符串,但这将帮助我选择正确的文本和正确的背景图像。

你能给我一个小例子或参考如何使用这个属性吗?我刚刚在 Stack Overflow 上找到了一个答案,但这并不能回答我的问题。

4

1 回答 1

2

只需在您的代码库上创建一个公共静态方法并使用 @BindingAdapter 进行注释。

下面是一个字体示例:

https://plus.google.com/+LisaWrayZeitouni/posts/LTr5tX5M9mb

由 rekire 编辑我最终使用了以下代码:

@BindingAdapter({"bind:badge"})
public static void setBadge(TextView textView, String value) {
    switch(value) {
        case "email":
            textView.setText(R.string.badge_email);
            textView.setBackgroundResource(R.drawable.bg_badge_email);
            break;
        // other cases
    }
}
于 2015-11-14T23:21:29.483 回答