Android DataBinding where to get context?
AndroidData BindingViewAndroid ContextAndroid Problem Overview
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
Thanks
Android Solutions
Solution 1 - Android
Also you can do something like this in your view using the current view context
as parameter.
...
android:text="@{yourModelHere.yourModelMethodHere(context)}"
...
Solution 2 - Android
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 - Android
> 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)}
.
Solution 4 - Android
To used string resources use this
this.yourView.getRoot().getResources().getString(R.string.your_string)