Android RecyclerView with Data Binding Library

Hi, in this small blog we’ll look at the Android Data Binding Library which we’re all excited about and implement a RecyclerView Adapter with it. Since there’s not so much of resources and samples on the web I think that for some of you this post would be very useful and interesting. So let’s get to it.

Adding Data

I don’t want to write all the basics since they’re all easy to find in official Data Binding Guide. But first I’d like to talk about little changes in the way you do it with Data Binding Library that you need to know. There are two approaches available to set data to you views. The first one is pretty similar to the regular, but you don’t need no Casts or findViewById, all the logic stays in Java

binding.fab.setOnClickListener(...);

Where fab is your view id in xml file. Nice! You just keep a binding reference. But it’s actually not binding nothing and we want something fancy, right? So let’s looks how we do it. By adding a variable tag in layout xml file

<layout>
<data>

<variable>
name="item"
type="com.example.item"
</variable>
</data>
<YourRootLayout...>
</layout>

and setting it by

binding.setItem(new Item());

If you confused sometimes about implementing the second approach, just use the first one. It’s still much better than findViewById.

Implementing RecyclerView.Adapter

It’s actually pretty simple to do, the only things you need to change from regular approach is inflating layout

ListItemBinding binding = DataBindingUtil.inflate(
LayoutInflater.from(context), R.layout.list_item, parent, false);
return new Holder(binding.getRoot());

and then in onBindViewHolder method you set the layout variable by

User user = list.get(position);
holder.binding.setUser(user);

And your Holder looks looks this

private class Holder extends RecyclerView.ViewHolder {
ListItemBinding binding;
    public Holder(View itemView) {
super(itemView);
binding = DataBindingUtil.bind(itemView);
}
}

That’s it! No more code required for you to write. Great, isn’t it? Now, if you want to handle clicks — just add

public Holder(View itemView) {
super(itemView);
binding = DataBindingUtil.bind(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
User user = binding.getUser();
...
}
});
}

So that’s it, it’s about me learning the technology and showing you guys the very basics you need to know to start implementing it by yourself without the additional bunch of code. If you like to see the GitHub sample you can get it here.

Here’s some useful resources:

Data Binding Guide

Android dev summit video on Data Binding

more video

If you want to hear more from me about Android development, here’s my blog where I make a new post every Monday. Looking forward to see you!

Thanks for reading and don’t forget to like it if you like and #BuildBetterApps!