Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android DataBinding where to get context?

People also ask

Is Android databinding deprecated?

Recently Android has announced that with Kotlin 1.4. 20, their Android Kotlin Extensions Gradle plugin will be deprecated and will no longer be shipped in the future Kotlin releases. Android Kotlin Extensions plugin brought with it two very cool features : Synthetics let you replace calls to findViewById with kotlinx.

How do I use Android databinding?

To convert your XML layouts into the Data Binding layout, follow the below steps: Declare a <layout> tag, which will wrap your existing layout file at the root level. Declare variables under the <data> tag, which will go under the <layout> tag. Declare necessary expressions to bind data inside the view elements.

Can I use both databinding and ViewBinding?

View binding doesn't support layout variables or layout expressions, so it can't be used to declare dynamic UI content straight from XML layout files. View binding doesn't support two-way data binding.

Should I use databinding or ViewBinding?

In short you can use ViewBinding to replace findviewbyid() effectively. If your project is however more complex and you need to add features like binding data to views, binding adapters e.t.c, use DataBinding.


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

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

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

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)}.