Android DataBinding where to get context?

梦想的初衷 提交于 2019-11-28 11:52:23

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}"/>

Also you can do something like this in your view using the current view context as parameter.

...
android:text="@{yourModelHere.yourModelMethodHere(context)}"
...
Yoel Polanco

A special variable named context is generated for use in binding expressions as needed. The value for context is the Context from the root View's getContext(). The context variable will be overridden by an explicit variable declaration with that name.

In other words, every time you need to pass the context just use "context" as in @{Object.method(context)}.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!