Making a RecyclerView Adapter with ViewBinding.

        You may already have used a RecyclerView before with kotlin extensions enabled. It used to be fun, and now the technology has headed bit further. Am gonna teach you the most recent and cleaner way to make a recyclerView adapter as you will be using ViewBinding. 

        In the course of me writing a couple of articles, I'll be referencing most stuff from a dummy app i published on google play. I called it Wakanda Forever Wallpapers. It's some kind of a gallery app comprising of a set photos i collected from the web. So in there i have implemented a RecyclerView with ViewBnding, an Options Menu as well plus so much more educative stuff you might wanna get your eyes on.

        Getting started with the making of our Adapter, you gotta make sure a list of items you want to display on your RecyclerView is at hand plus i assume you have a complete idea on how you deal with the RecyclerView widget and have created an item layout for it as well. So in my case i had a list of images on my drawable folder and so created an object and stashed my images in there.

object IsiyoBadilika {
    fun feedYaPichaProvider(): ArrayList {
        val feedYaPicha: ArrayList = ArrayList()
        feedYaPicha.add(R.drawable.pre1)
        feedYaPicha.add(R.drawable.pre2)
        feedYaPicha.add(R.drawable.pre3)
        feedYaPicha.add(R.drawable.pre4)
        feedYaPicha.add(R.drawable.pre5)
        feedYaPicha.add(R.drawable.pre6)
        feedYaPicha.add(R.drawable.pre7)
        feedYaPicha.add(R.drawable.pre8)
        feedYaPicha.add(R.drawable.pre10)
        return feedYaPicha
    }
}

So that's a sample from my list of items am planning to display on the RecyclerView. As you can see, it's an array list of images. Yours could be strings and stuff. It depends on your app design, so don't you worry about slight differences. A sample of my widget is also down below so you can take a look at it, just to have a wider perspective of what am trying to do right now.

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rez"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:listitem="@layout/individual_photo_design"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="2"/ >

Again that's my widget right there. Make yours available as well. Having all that all setup we should be ready to kickoff with preparing our adapter alongside View Binding. Let's begin with step one.

1. Create a class for our Adapter

        The process should not be terrifying, because the class am saying you have to create should just be an ordinary class but only the naming. Try and make the name of your class as relevant as it can be, because it's for our adapter class

 class AdapterYaWakanda(private val mahalia: Context, private val feedYaPicha: ArrayList<Tnt>): RecyclerView.Adapter<AdapterYaWakanda.AdapterForever>() {  

 }

The name of my adapter class is what i can say relevant to my project, so make yours too. I passed in a Context, and a list of images i showed you a couple of paragraphs ago. The most important part you wanna have i just passing in the list, worry less about my context cos i had some uses with it that you may or may not have. As you may have seen, our adapter class inherits from RecyclerView.Adapter within it we can be able to see that the name of our class is passed but only we see something strange on dot front of it. What is that?. Well it's an inner class we have not created yet, so it's something we yet have to make next. 

 2 Make an inner class 

        The inner class am talking about right now is the actual AdapterForever you saw on the snippet above. We gonna make an inner class and we gonna implement some functionalities in it. 

 inner class AdapterForever(private val kiunganishi: IndividualPhotoDesignBinding): RecyclerView.ViewHolder(kiunganishi.root){
fun ninaBind(picha: Int){
kiunganishi.picha.setImageResource(picha)
kiunganishi.picha.setOnClickListener {
mahalia.startActivity(Intent(mahalia, MainActivity2::class.java)
.putExtra("picha", picha))
}
}
}

Backing up what you are seeing right now, t's the class  i have been talking about, only that i have passed some-kind of a parameter kiunganishi of type ?, well it's of the type your item layout binding. My item layout i called IndividualPhotoDesign, so find a more cooler name for your item layout and it has to look like CoolerNameBnding. Again the class has to inherit from RecyclerView but this times it's dot viewholder() which will require a view.. Luckily we got a bind to our view in place already, it's kiunganishi.root.  The function you see in there is just a custom function. You create one of your own and pass in an individual data you want to appear on each item of your RecyclerView. My image resources in drawable folder are kept as integers and so i pass the images as some-kind of ints. 

        The kiunganishi allows us to access views from the item layout and so we can bind the data to these. To this point you now clearly understand what the function does in there. that's good, so let's keep moving..

3. getItemCount

The RecyclerView needs to know the count of items it will have to display, and i really think this makes a perfect sense, coz if you wanna handle a task, then the first thing you wanna know is how much energy you gonna spend on that task. So make the adapter capable of doing this by overriding a method known as getItemCount. The method returns an integer, simply because a more realistic count of items is always in counting digits, meaning that it has to return a positive integer. We get the list of items from the list we passed during early stages of making our adapter class.
 
override fun getItemCount(): Int {
return feedYaPicha.size
}
 just a reminder for all of us who might have forgotten. The .size is used there to determine the size of the array i just passed. So whatever the size of your list, it's always going to return the number of items that are available in there.
 

 4. Override onCreateViewHolder

       We are going to inflate our recycler view using this method. The method returns a value, but the value it returns is the inner class we created some moments ago. It's name according to how i named mine was AdapterForever, if you named yours different, it definitely have to look your way. So the values you see fixed in there should not surprise your a lot. The first thing you are looking at in there is your item layout binding class which we gonna use to perform an inflation using a layout inflater followed by a dot location of where we intend to inflate our View holder, which is the parent. One thing to remember is that you have a choice of attaching to root, but it's a more better practice setting this to false, as i just did. You should too, it's safer that way.

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AdapterForever {
return AdapterForever(IndividualPhotoDesignBinding
.inflate(LayoutInflater.from(parent.context), parent, false))
}

5. Override onBindViewHolder

        What onBindViewHolder does is simply to monitor that the data which is bound to the screen. During times when you scroll you immediately begin setting sight to view holders that were used for rows that went off screen and you have to replace old data that they held with new data. This is why the widget takes advantage of the fact that as you scroll and new rows come on screen also old rows disappear off screen. Instead of creating new view for each new row, an old view is recycled and reused by binding new data to it. In summary the method usually gets called when your mobile screen is fully populated with data and that newer data needs to be displayed, this is commonly a triggered action due to a scrolling event from the user. It comes in with a position attribute so yu wanna use this attribute to monitor the positions to where the data has been displayed upto, then call the function to bind indivdual data that is in that position.
 
override fun onBindViewHolder(holder: AdapterForever, position: Int) {
holder.ninaBind(feedYaPicha[position])
}
Up to this point, your adapter is ready to go,  hope you've learned something, and am really hoping it's so because it's one reason i have spent more than three hours now just detailing out every piece on this article. Leave a comment on what you want me to write about next, but also i have some other beautful artcles i have written about requesting run time read external storage permission and adding options menu on your appbar. Make sure to check them out if you please
 
Stay awesome,
#Sam        

0 Comments