使用Android Data Binding传递参数给方法

3
首先,这个问题不是“onClick”事件参数传递的情况。 我有一个DateUtil类,其中有一个以下方法:
public static String formatDate(long date) {
        SimpleDateFormat dateFormat;
        dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        Calendar c = Calendar.getInstance();

        dateFormat.setTimeZone(TimeZone.getDefault());
        c.setTimeInMillis(date);
        return dateFormat.format(c.getTimeInMillis());
    }

我的模型 CommentEntity 具有以下属性:

 private int id;
 private int productId;
 private String text;
 private Date postedAt;

现在,在我的一个布局中,我正在显示评论。

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable name="comment"
                  type="com.example.entity.CommentEntity"/>
        <variable
        name="dateUtil"
        type="com.example.util.DateUtil"/>

    </data>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:layout_alignParentRight="true"
                android:layout_below="@id/item_comment_text"

                //This line gives error for data binding
                android:text="@{dateUtil.formatDate(comment.postedAt.time)}"/>
</layout>

我收到的错误信息是:

在类long中找不到方法 formatDate(com.example.util.DateUtil)

如果我修改formatDate()方法,使其默认使用当前时间,因此在数据绑定中删除参数传递,那么它将完美地工作。
所以我是否做错了什么或者这是一个bug?
请提供解决方案,以便在数据绑定中传递参数给方法。
2个回答

5
尝试以下方法:
  1. 不要直接从XML数据绑定中获取您的DateUtil类对象。

CommentEntity模型类中创建一个BindingAdapter方法,如下所示:

@BindingAdapter("android:text")
public static void setPaddingLeft(TextView view, long date) {
    view.setText(DateUtil.formatDate(long));
}

然后在xml中使用如下代码:
<TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_alignParentRight="true"
            android:layout_below="@id/item_comment_text"
            android:text="@{comment.postedAt.time}"/>

Explanation:

当您想要基于数据模型应用一些自定义逻辑到您的视图(view)时,您需要使用BindingAdapter来完成此任务。因此,您可以提供一些自定义标签或使用任何默认的android:标签,在该标签上设置逻辑。

我拒绝使用DateUtil作为绑定适配器,因为您可能在其他地方也会使用其方法。建议您在模型中创建新方法,以便核心逻辑保持不变。(您可以将您的DateUtils用于此逻辑,但您需要将其设置为BindingAdapter)。


太棒了!感谢您的精彩解释。但是为什么我们不能在数据绑定中传递参数呢? - Parikshit Chalke

0

既然你想在DateUtil中使用静态方法,那么你应该进行导入:

<data>
    <variable ... />
    <import type="foo.bar.DateUtil"/>
</data>

并且在TextView中:

<TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:layout_alignParentRight="true"
                android:layout_below="@id/item_comment_text"
               //use DateUtil directly-
                android:text="@{DateUtil.formatDate(comment.postedAt.time)}"/>

你的错误在于试图将其用作变量 - 这告诉数据绑定期望此类实例在您的UI类(Fargment/Activity)中的某个位置进行绑定


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接