且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android DataBinding在哪里可以得到上下文?

更新时间:2023-11-15 08:19:04

  @BindingAdapter({timeMillis,dateFlags})
public static void setDateText(TextView view,int timeMillis,int dateFlags){
view.setText(DateUtils.formatDateTime(view.getContext(),timeMillis,
dateFlags));
}

然后在您的TextView中使用它:

 < TextView ... app:timeMillis =@ {timeVar}app:dateFlags =@ {dateFlags}/> 


I have TextView for showing time. I want to use Android's DataBinding plugin. For formatting time I am using DateUtils.formatDateTime(context, int, int) method which takes Context instance. Is it possible to get context include element? Or do I have to use old school way?

Thanks

Thought I should answer instead of putting in a comment. You'll have more options when rc2 is released. In rc1, you can pass the context in a variable to the Binding, then pass it as a parameter to the method. Alternatively, you can create a custom attribute for data binding:

@BindingAdapter({"timeMillis", "dateFlags"})
public static void setDateText(TextView view, int timeMillis, int dateFlags) {
    view.setText(DateUtils.formatDateTime(view.getContext(), timeMillis,
                 dateFlags));
}

And then use it in your TextView:

<TextView ... app:timeMillis="@{timeVar}" app:dateFlags="@{dateFlags}"/>