Par*_*lke 2 android android-databinding
首先,这个问题不是'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());
}
Run Code Online (Sandbox Code Playgroud)
我的模型CommentEntity具有以下属性:
private int id;
private int productId;
private String text;
private Date postedAt;
Run Code Online (Sandbox Code Playgroud)
现在,在布局之一中,我将显示注释。
<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>
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
在类long中找不到方法formatDate(com.example.util.DateUtil)
现在,对于相同的情况,如果我修改formatDate()方法,因为默认情况下它将花费当前时间,因此删除了数据绑定中传递的参数,它将可以完美地工作。
那么我是在做错什么还是错误?
请提供在数据绑定中将参数传递给方法的问题的解决方案。
请尝试以下方法:
DateUtil直接从xml中的数据绑定中获取类对象在模型类中创建一个BindingAdapter方法,如下所示:CommentEntity
@BindingAdapter("android:text")
public static void setPaddingLeft(TextView view, long date) {
view.setText(DateUtil.formatDate(long));
}
Run Code Online (Sandbox Code Playgroud)
然后使用如下所示的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}"/>
Run Code Online (Sandbox Code Playgroud)
说明:
当您想为基于数据模型的视图应用一些自定义逻辑时,您需要使用BindingAdapter来完成这项工作。因此,您可以提供一些自定义标签或使用需要在其上设置逻辑的任何默认标签。android:
我拒绝了您使用DateUtil绑定适配器,因为您可能也在其他地方使用了它的方法。因此建议在模型中为该逻辑创建新方法,以使核心逻辑保持不变。(DateUtils不过,您可以将您的逻辑用于此逻辑,只需将其设置为BindingAdapter即可)。
| 归档时间: |
|
| 查看次数: |
1062 次 |
| 最近记录: |