Kotlin Lambda Functions For RecyclerView Adapter Callbacks in Android
Last Updated :
29 Mar, 2022
Are you using old lengthy java fashioned way of creating & handling callbacks in Android with Interfaces? If yes then it's a very good time to switch on Kotlin Lambda Functions or Higher Order Functions to create & handle callbacks. It's a much short, simpler & easy way.
Let's first quickly have a look at older java style way
Remember when you need to implement click functionality on your RecyclerView items, you create an interface that has all the methods to handle your RecyclerView items different clicks and you implement all those functions of interface inside your activity/fragment to perform some actions (for ex: to navigate from current screen to another or something else). And then you pass the reference of that interface into your adapter via the constructor. Then we use that interface in the Adapter to invoke/call its functions to generate callbacks inside activity/fragment. Now look how long the process is and here comes the power of Kotlin in play... Let's see
Kotlin Lambda Functions for adapter callbacks
First, say bye to the lengthy interface way.... we will now add the lambda function as an argument in our adapter's constructor. We are taking MoviesAdapter as an example that takes moviesList & lambda function named 'onItemClicked' as an argument & in our lambda function 'onItemClicked' we have added movie object as an argument so that we can receive this movie object in this lambda function's callback in our fragment/activity.
Kotlin
class MoviesAdapter(
private var moviesList: List<Movie>,
// Here we have added lambda function
// named 'onItemClicked' as an argument
// that will itself take movie object as an
// argument & will return unit means nothing
private var onItemClicked: ((movie: Movie) -> Unit)
) : RecyclerView.Adapter<MoviesAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
// Just to show as an example we took layout
// 'MovieItem' as recyclerview items/views.
val binding = MovieItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// getting a movie from movieList &
// passing in viewholder's bind function
holder.bind(moviesList[position])
}
inner class ViewHolder(val binding: MovieItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(movie: Movie) = binding.apply {
// Just setting movie details to
// movieName & movieDescription textviews
tvMovieName.text = movie.name
tvMovieDescription.text = movie.description
// Adding clickListener to
// root layout of this item
root.setOnClickListener {
// Invoking this lambda function so that
// it can give callback in our activity/fragment
// We are also passing movie object
// in it while invoking/calling it
onItemClicked(movie)
}
}
}
override fun getItemCount(): Int {
return languageList.size
}
}
In this example, we are using Viewbinding in RecyclerView Adapter. Now let's move inside Viewholder's bind function, inside it, we are simply setting movie details like movie name, description to RecyclerView items and we have to add click functionality to every RecyclerView item so that we can perform some action on click. So, in clickListener of our item's root, we are actually invoking our lambda function onItemClicked & passing movie in it. So this way we'll receive a callback in our fragment/activity as it'll get invoked here on item click. Now let's see how...
Let's create the adapter's object & pass Lambda Function in it
We are taking MovieListFragment as an example here:
Kotlin
class MovieListFragment : Fragment() {
// Declaring moviesAdapter with lateinit
private lateinit var moviesAdapter: MoviesAdapter
// using viewbinding
private var _binding: FragmentMovieListBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMovieListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Assume that getMoviesList() is returning
// list of movies let's say from api call
val moviesList : List<Movie> = getMoviesList()
// Setting up movies recyclerview
binding.moviesRecyclerView.layoutManager = LinearLayoutManager(requireContext())
binding.moviesRecyclerView.setHasFixedSize(true)
// Instantiating moviesAdapter & passing
// lambda function in it's constructor
moviesAdapter = MoviesAdapter(moviesList) { it: Movie ->
// Here we'll receive callback of
// every recyclerview item click
// Now, perform any action here.
// for ex: navigate to different screen
}
// Setting adapter to moviesRecyclerView
binding.moviesRecyclerView.adapter = moviesAdapter
}
}
Here, we are simply instantiating moviesAdapter so it'll require us to pass the list of movies & lambda functions in its constructor. So now, here in the lambda function block, we are getting a movie object, which means whenever this lambda function will be invoked from the adapter, we'll receive a callback here with the movie object and now we can perform any action that we want under this lambda function block. That's it, that's how we use Kotlin Lambda Functions for RecyclerView adapter callbacks instead of interfaces.
Note: We can use these lambda functions for creating/handling callbacks not only in recyclerview's adapter but wherever we want this type of functionality in our project.
Similar Reads
How to Use View Binding in RecyclerView Adapter Class in Android?
View Binding is a part of Android Jetpack which provides the views to bind with the classes by replacing the findViewById() method in a null safe way. In this article, we will see its implementations in the Adapter class of RecyclerView. Note: This project is implemented using the Kotlin language. S
5 min read
DiffUtil in RecyclerView in Android
Have you ever created a List in Android? What did you use to make it? ListView or RecyclerView are two types of views. If you are an Android Developer it's sure you've used RecyclerView at some point. In this article, we'll go through how to update the RecyclerView with DiffUtils. What exactly is Re
5 min read
How to add Bullet list in a RecyclerView in Android?
Recycler View allows us to show a list of items but to convert our list into the bulleted list we have to do some extra work. You can do this task by following these simple steps given below:- Add the support Library in build.gradle file for Recycler View in the dependencies section. XML <depend
2 min read
Android RecyclerView in Kotlin
In this article, you will know how to implement RecyclerView in Android using Kotlin . Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ab
4 min read
How to Update RecyclerView Adapter Data in Android?
RecyclerView is used in many android applications to display the list of data within android applications. We can dynamically add or remove data from our recycler view. For updating data in the RecyclerView, we have to use the Adapter class. Adapter handles all the data within our recycler view. In
6 min read
How to Create Options Menu for RecyclerView in Android using Kotlin?
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item that can be custom
6 min read
How to Build a Facebook Like Custom RecyclerView in Android?
We have seen implementing RecyclerView in Android with simple data inside our app. In this article, we will take a look at the implementation of Facebook like Custom RecyclerView in Android. What we are going to build in this article? We will be building a simple application in which we will display
9 min read
Expandable RecyclerView in Android with Kotlin
In this article, we will get to know how to implement the expandable RecyclerView. In General, we will show the list of items in the listview but in some situations like if you want to show the sub-list items, then we have to use an expandable list. See the below image for a better understanding. ex
7 min read
How to Implement RecyclerView in a Fragment in Android?
In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application. Â A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It h
12 min read
How to Animate RecyclerView Items in Android?
RecyclerView Item animation is one of the modern features that we can add to our Android app, the basic working of this is when any user opens our app then the data items that are present in recycler view will animate and then it will show to the user.it is so easy to implement also it can enhance t
5 min read