Android DataBinding where to get context?

AndroidData BindingViewAndroid Context

Android 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 element? Or do I have to use old school way?

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbakuaView Question on Stackoverflow
Solution 1 - AndroidepoolView Answer on Stackoverflow
Solution 2 - AndroidGeorge MountView Answer on Stackoverflow
Solution 3 - AndroidYoel PolancoView Answer on Stackoverflow
Solution 4 - AndroidAshraf AminView Answer on Stackoverflow