Data Binding: BindingAdapter

Paul Woitaschek
YAZIO Engineering
Published in
2 min readJan 31, 2016

For a long time I did not investigate further into https://developer.android.com/tools/data-binding/guide.html but recently it just got my attention.
Just like Kotlin or RxJava this was something that was constantly trying to get my attention so I decided to give it a try and to see how it works while writing my new notes app.

And I must say: I’m impressed.

I applied it on the ViewHolder of my RecyclerView and reduced the boilerplate code by about 50%. But there were some issues.

Issues

The biggest I had was manipulating the view. The grey text could be simply archieved by setting the view enabled based on the view model:

android:enabled=”@{!model.done()}”

As the text was set to @color/abc_primary_text_material_light from the support library this automatically works. But how to set the strike through? I did not wanted to call all these `findViewById` any more as that would defeat the purpose of DataBinding.

Solution

It turned out there was a simple solution, called BindingAdapter> https://developer.android.com/reference/android/databinding/BindingAdapter.html
Basically you just define a static method and annotate it as a binding adapter. So for strikeThrough it is:

@BindingAdapter(“text:strike”)
public static void setStrike(TextView text, boolean strike) {
if (strike) {
text.setPaintFlags(text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else {
text.setPaintFlags(text.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
}
}

So now you can set it just as a regular xml attribute:

android:strike=”@{model.done()}”

--

--