An Idiot’s guide to Android RecyclerView and DataBinding
In this part, we are going to hook our RecyclerView
with DataBinding
. Why, you may ask, because it’s AWESOME. In this we are going to show bunch of movies with their name and description.
- Enable
DataBinding
in your appbuild.gradle
file
android {
...
dataBinding {
enabled = true
}
}
2. In your activity_main.xml
define a RecyclerView tag
3. Create a Movie
pojo class, We need getters function to access variable in our xml and setters are used when you want two way DataBinding.
4. Create a layout file for individual movie item, we named it item_movie.xml
5. Now comes the magic, wrap your item_movie.xml
LinearLayout
into <layout>
component
6. Now we need our Movie
pojo variable in our item_movie.xml
so that we can access title
and descripition
directly, for that we need to provide <variable>
tag inside our xml
Note: You need to provide correct path for
Movie
pojo in the type attribute and the name attribute that you set will be used in code to provide an instance ofMovie
to individual row.
7. Now you can directly access member variables of Movie
pojo into xml using @{} annotation
we have replaced
- android:text="Movie name"
+ android:text="@{movie.title}"
If you are wondering we have made member variable of class
Movie
private and we are able to usemovie.title
directly, it’s because we have provided getter function for title and DataBinding is smart to translatemovie.title
intomovie.getTitle()
8. Let’s work on adapter side now, create a class MovieAdapter
which contains an inner static class MovieViewHolder
that extends RecyclerView.ViewHolder
9. Now extend your MovieAdapter
class to RecyclerView.Adapter<MovieAdapter.MovieViewHolder>
and implement all the method by clicking on red bulb appearing on Android Studio
10. Create a constructor that will accept List<Movie> movieList
which contains all the movies that we want to show.
11. Now all that is left is to inflate the layout and bind each instance of Movie
to our row in onCreateViewHolder
and onBindViewHolder
12. We will use Databinding
in MainActivity.java
also to get access to RecyclerView
and set adapter. Again in your activity_main.xml
enclose your code into <layout/>
tag
13. Inflate activity_main.xml
in MainActivity.java
using databinding
14. Now let’s initialize our RecyclerView
and create instance of MovieAdapter
and set adapter.
Phew! that was a lot. The motive of this article was to have a handy guide to look back whenever you feel stuck. Just bookmark it to have a handy reference. This article has been shamelessly stolen from
If you want to setup RecyclerView without databinding checkout:
If you enjoyed this article, feel free to hit that clap button 👏 to help others find it.