【问题标题】:How to define a custom BindingMethod for a TextView?如何为 TextView 定义自定义 BindingMethod?
【发布时间】:2016-02-16 07:38:27
【问题描述】:

我开始使用新的数据绑定 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 上找到了one answer,但这并不能回答我的问题。

【问题讨论】:

  • 您在候选人演讲中写下了“我节省的空档时间”。而不是“整个时间”。
  • 哦,不,不再。谢谢!

标签: android data-binding android-databinding


【解决方案1】:

只需在您的代码库上创建一个公共静态方法并使用 @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
    }
}

【讨论】:

  • 哦,男孩是世界之小,我参加了她在伦敦的演讲,在那里她也展示了代码。明天我会检查的。
  • 我添加了我现在使用的代码。感谢您指出该 google+ 帖子!
猜你喜欢
  • 2012-03-17
  • 2011-04-19
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多