Handling onClick behavior with the Jetpack paging library

Zed
ProAndroidDev
Published in
2 min readNov 4, 2020

--

Photo by Elia Pellegrini on Unsplash

While migrating to the new Paging3 library in the Jetpack suite of libraries, I ran into a problem, my onClickListener on the items of my RecyclerView was no longer able to get the data of the clicked item as the viewModel returned a flowable instead of a List<DataType> which can be directly used in the PagingDataAdapter using the DiffUtil.ItemCallback.

In order to setup a click listener which can be implemented in the activity/fragment, I had to solve the problem by creating a custom class to provide the click listener to the adapter which could then be provided to the adapter at the time of creation of the RecyclerView in the activity/fragment.

Here are the steps that you can follow to setup a click listener with the data provided by the underlying ViewHolder.

  1. Create a data class to provide the click listener to the adapter.

2. Provide the class as an constructor argument in the adapter, which will be later provided in the calling activity or fragment.

3. Attach the click listener on the current view in the ViewHolder

4. Provide the required data accessible in the onBindViewHolder() methods

That is all that is needed in the adapter, here is how the adapter will look like:

5. Now all that remains is to set up the listener in the fragment/activity that uses adapter, in my case I am using the androidx.navigation library to navigate to a different fragment when the RecyclerView item is clicked.

That’s all!, if you have any confusion regarding the implementation, you can check out Wallportal where this has been implemented along with other Jetpack libraries.

The reason I wrote this article is that there was not documentation or articles online showing this implementation, hope someone finds it useful!

--

--