问题描述
我有 TextView
用于显示时间.我想使用Android的DataBinding插件.
I have TextView
for showing time. I want to use Android's DataBinding plugin.
对于格式化时间,我使用 DateUtils.formatDateTime(context, int, int)
方法,该方法采用 Context
实例.是否可以获取上下文包含元素?还是我必须使用老派的方式?
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?
谢谢
推荐答案
我想我应该回答而不是发表评论.rc2 发布后,您将有更多选择.在 rc1 中,您可以将变量中的上下文传递给 Binding,然后将其作为参数传递给方法.或者,您可以为数据绑定创建自定义属性:
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));
}
然后在你的 TextView 中使用它:
And then use it in your TextView:
<TextView ... app:timeMillis="@{timeVar}" app:dateFlags="@{dateFlags}"/>
这篇关于Android DataBinding 从哪里获取上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!