Android kotlin recyclerview item click

[Tutorial] How to Implement a Click Listener to an Android Recycler View

Recently we shared an article on how to create your first Recycler view with android in Kotlin, and In this engaging post, We would like to share you with an interesting addition to that. A Recycler View is an advanced version of ListView in android with interesting features that you help you make an interesting UI and UX for your android application. And if you want to make it clickable and respond to the user interaction follow this tutorial to the end, In here you will learn how to set up a click listener to an android Recycler View.

Let’s start with our basic setup by implementing a simple recycler view you can refer our Other guide on how to make an android recycler view with kotlin for a detailed and step by step instructions. Here we will only cover a part of that, think this as a part of the previous tutorial.

Android Recycler View Click Listener With Kotlin:

Add a simple recycler view to your layout, and set up an adapter to it, if your following from the previous tutorial, you can use the same recycler view adapter to it. The concept that we are going to implement to get a click listener to our Recycler view is by using the Callback functionality.

In computer programming, a callback, also known as a «call-after»[1] function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time.

Source : Wikipedia

You can get a gist about callback from Wikipedia’s explanation, although it would make more sense once you implemented it. To implement Callback to our recycler view, we need to have an interface.

Читайте также:  Php check if date is between dates

Create a new Kotlin file and define it as interface and name it as RecyclerViewClickListener and add a new function as onClicked() and pass some data like position and a string of the android version name.

interface RecyclerViewClickListener

fun onClickName(position:Int,versionName:String)

>

Now implement this interface into your main activity.like below

class MainActivity : AppCompatActivity() ,RecyclerViewClickListener

>

In Kotlin we extend a class with ‘:‘ colon symbol and if we are wan to implement an interface which can be included in the same line followed by a ‘,‘ comma symbol. You can implement more than one interface but you cannot extend more than one class.

Once you have implemented the interface you will get a red squiggly line on the class name, to remind you that you have to override those member functions which is onClickName(position: Int,verisonName: String). Tip: Place the cursor over the class name and Press Alt + Enter it will open a dialog box with a list of functions that you have to override. In that overridden function make a toast message to show the version number that we just clicked, You can refer our tutorial to Show Toast Message from You Activity With Kotlin here. After that, your class will be like below

class MainActivity : AppCompatActivity() ,RecyclerViewClickListener

override fun onCreate(savedInstanceState: Bundle?)

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

val androidVersionRecycler = findViewById(R.id.androidVersionRecycler)

androidVersionRecycler.adapter = AndroidVersionRecyclerAdapter(resources.getStringArray(R.array.anroid_names),this)

>

override fun onClickName(position: Int, versionName: String)

Toast.makeText(applicationContext,»Clicked Android version $versionName at position = $position»,Toast.LENGTH_SHORT).show()

>

>

If you look in the above code that we passed a second parameter to our adapter which is «this» what it actually referring is the implemented click listener, why we pass that it because we use this «this» reference to call the function in the future as a callback. Okay, let’s go deeper.

Now You can use our previous tutorial to create an Adapter which accepts two parameters one is the string array and a click listener interface

AndroidVersionRecyclerAdapter.kt

class AndroidVersionRecyclerAdapter(private val versionList:Array, private val recyclerViewClickListener: RecyclerViewClickListener)

:RecyclerView.Adapter()

override fun onCreateViewHolder(

parent: ViewGroup,

viewType: Int

): AndroidVersionRecyclerViewHolder

return AndroidVersionRecyclerViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.recycler_list_view,parent,false))

>

override fun getItemCount(): Int = versionList.size

override fun onBindViewHolder(holder:AndroidVersionRecyclerViewHolder, position: Int)

holder.bind(position,versionList[position],recyclerViewClickListener)

>

>

Actually, in this adapter, we are not going to do any much of work because our view is being rendered by the view holder so we are just passing our click listeners reference to the view holder. To access the parameters send through the constructor in kotlin we have to put some efforts in general we cannot access those parameters directly like we access the parameters of the function to access the constructor parameter it must have the var or val declaration so that it can be accessed inside the class. Once you got the variable now send it to the bind function as a parameter.

Now In your view holder’s bind function get the reference to the click listener create a new setOnClickListernt to your view it could be anything either a TextView or Button anything, and inside that scope call the onClickName function with the passed as recyclerViewClickListerer, And this is what callback is, that you call that function in the future when you needed but is implemented already.

class AndroidVersionRecyclerViewHolder(view: View): RecyclerView.ViewHolder(view)

val nameTextView = view.findViewById(R.id.versionNames)

fun bind(position:Int,versionName:String,recyclerViewClickListener: RecyclerViewClickListener)

nameTextView.text = versionName

nameTextView.setOnClickListener

recyclerViewClickListener.onClickName(position,versionName)

>

>

>

Above click, the listener is a normal click lister on a button which you can learn from here How to add click listener to a button in kotlin android , in the execution of the button call the necessary interface method so that it could callback that method. In this case, it will call the method in our activity as the recyclerviewClickLister holds the reference of the interface in our activity and since we are calling the method it will also call that method. This will show a Toast Message.

Pro Tip: If you are copy-pasting this code you might see the import statements missing, to quickly import, just click the class name and press Alt + Enter

Get the complete code here: Github Link

BasicRecyclerView

android recyclerview click listener kotlin

recyclerview item click listener in fragment

how to pass data from recyclerview adapter to fragment in android

recyclerview item click listener kotlin

kotlin recyclerview onitemclicklistener github

Источник

How to add onClick to RecyclerView list items in Kotlin

If you are here chances are you already know how to create a RecyclerView, if not take a look at How to create a RecyclerView with custom Adapter in Kotlin.

Overview

Kotlin has higher order functions, which are functions that can have functions as parameters or return functions. So the idea here is that

  1. Create a function onListItemClick that handles the click event in the UI(Activity/Fragment). The reason you want to create a function here is because list item clicks usually result in UI changes like moving to a different Activity/Fragment, show a Toast/Snackbar, etc.
  2. Pass this function as argument to the adapter followed by passing the function again to the ViewHolder while creating them.
  3. In the ViewHolder make the ViewHolder class implement View.OnClickListener followed by implementing the required onClick method. In the onClick method call the onListItemClick function.

Now when a list item is clicked, the ViewHolder handles the click and calls the method defined in our Activity/Fragment.

As an example I will be adding onClick to RecyclerView in a simple app that displays a list of Github repositories.

Step 1: Create a function that handles click in the UI

Here I am just displaying a Toast, you may navigate to another Activity or Fragment.

class MainActivity : AppCompatActivity() ... ... // In MainActivity.kt private fun onListItemClick(position: Int)  Toast.makeText(this, mRepos[position].name, Toast.LENGTH_SHORT).show() > >

Step 2: Add a new function as argument to the Adapter

Change signature of the Adapter so that it accepts a function as an argument.

class GithubRepositoryAdapter(private val onItemClicked: (position: Int) -> Unit) : RecyclerView.AdapterRepositoryViewHolder>()  private val TAG = javaClass.simpleName private var mAllRepositories: ArrayGithubRepository>? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RepositoryViewHolder  val context = parent.context val inflater = LayoutInflater.from(context) val view = inflater.inflate(R.layout.repository_list_item, parent, false) return RepositoryViewHolder(view, onItemClicked) >

Now make sure to pass onListItemClick to the adapter in the UI.

class MainActivity : AppCompatActivity()  ... ... override fun onCreate(savedInstanceState: Bundle?)  ... ... mRepositoryRecyclerView = findViewById(R.id.rv_repo_list) mGithubRepositoryAdapter = GithubRepositoryAdapter position -> onListItemClick(position) > mRepositoryRecyclerView.adapter = mGithubRepositoryAdapter > >

Step 3: Add a new function as argument to the ViewHolder

Similarly change the ViewHolder parameter and accept a function. Also implement View.onClickListener and implement the onClick method. Finally call the function inside it like so:

class RepositoryViewHolder( itemView: View, private val onItemClicked: (position: Int) -> Unit ) : RecyclerView.ViewHolder(itemView), View.OnClickListener  ... ... init  itemView.setOnClickListener(this) > ... ... override fun onClick(v: View)  val position = adapterPosition onItemClicked(position) > >

Hopefully you feel more comfortable with adding onClick to RecyclerViews. If you find any errors, have feedback or just want to say hi please don’t hesitate to leave a comment below.

This website may contain affiliate links, meaning I may receive a small commission for products purchased through these link at no extra cost to you.

Источник

Part 4 – Click Handler

Coding in Flow

In part 4 of the Kotlin RecyclerView tutorial, we will learn how to handle click events on the single items in our RecyclerView.

Links & Dependencies ExampleAdapter.kt MainActivity.kt activity_main.xml example_item.xml ExampleItem.kt

RecyclerView & CardView dependencies:

package com.codinginflow.recyclerviewexample import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.example_item.view.* class ExampleAdapter( private val exampleList: List, private val listener: OnItemClickListener ) : RecyclerView.Adapter() < override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder < val itemView = LayoutInflater.from(parent.context).inflate(R.layout.example_item, parent, false) return ExampleViewHolder(itemView) >override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) < val currentItem = exampleList[position] holder.imageView.setImageResource(currentItem.imageResource) holder.textView1.text = currentItem.text1 holder.textView2.text = currentItem.text2 >override fun getItemCount() = exampleList.size inner class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener < val imageView: ImageView = itemView.image_view val textView1: TextView = itemView.text_view_1 val textView2: TextView = itemView.text_view_2 init < itemView.setOnClickListener(this) >override fun onClick(v: View?) < val position = adapterPosition if (position != RecyclerView.NO_POSITION) < listener.onItemClick(position) >> > interface OnItemClickListener < fun onItemClick(position: Int) >>
package com.codinginflow.recyclerviewexample import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.activity_main.* import kotlin.random.Random class MainActivity : AppCompatActivity(), ExampleAdapter.OnItemClickListener < private val exampleList = generateDummyList(500) private val adapter = ExampleAdapter(exampleList, this) override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) recycler_view.adapter = adapter recycler_view.layoutManager = LinearLayoutManager(this) recycler_view.setHasFixedSize(true) >fun insertItem(view: View) < val index = Random.nextInt(8) val newItem = ExampleItem( R.drawable.ic_android, "New item at position $index", "Line 2" ) exampleList.add(index, newItem) adapter.notifyItemInserted(index) >fun removeItem(view: View) < val index = Random.nextInt(8) exampleList.removeAt(index) adapter.notifyItemRemoved(index) >override fun onItemClick(position: Int) < Toast.makeText(this, "Item $position clicked", Toast.LENGTH_SHORT).show() val clickedItem = exampleList[position] clickedItem.text1 = "Clicked" adapter.notifyItemChanged(position) >private fun generateDummyList(size: Int): ArrayList < val list = ArrayList() for (i in 0 until size) < val drawable = when (i % 3) < 0 ->R.drawable.ic_android 1 -> R.drawable.ic_audio else -> R.drawable.ic_sun > val item = ExampleItem(drawable, "Item $i", "Line 2") list += item > return list > >
package com.codinginflow.recyclerviewexample data class ExampleItem(val imageResource: Int, var text1: String, var text2: String)

Find the best programming tutorials on tuthub.io

Источник

Оцените статью