Android DataBinding where to get context?
Solution 1:
Also you can do something like this in your view using the current view context
as parameter.
...
android:text="@{yourModelHere.yourModelMethodHere(context)}"
...
Solution 2:
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}"/>
Solution 3:
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)}
.