Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Interface in my Kotlin RecylerView adapter and getting callback in Kotlin Activity

Tags:

kotlin

This is my KotlinRecyclerView adapter class

  class ListAdapter(var c: Context, var lists: ArrayList<Employee>,
     itemClickListener: Any?): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
      override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
       var v = LayoutInflater.from(c).inflate(R.layout.list_layout, parent, false)
        return Item(v)
      }
      override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
       (holder as Item).bindData(lists.get(position))
      }
      override fun getItemCount(): Int {
        return  lists.size;
        }
     class Item(itemView: View) : RecyclerView.ViewHolder(itemView) {
      fun bindData(_list: Employee)
      {
       itemView.textViewfirstname.text = _list.firstName
       itemView.textViewlastname.text = _list.lastName
      }
     }
    }

This is my Kotlin activity code

list.adapter = ListAdapter(this, getLists())
like image 789
Prashant Andhale Avatar asked Oct 12 '17 07:10

Prashant Andhale


People also ask

How do I declare a adapter in Kotlin?

Go to app > java > package name > right-click > New > Kotlin class/file and name that file as CustomAdapter and then click on OK.


1 Answers

You can pass interface like

list.adapter = ListAdapter(this, getLists(), object : ItemClickInterfaces {
                    override fun itemClick() {
                        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                    }
               })

In adapter side you can use like this :

 class ListAdapter(var context: Context, var lists: ArrayList<Employee>,  var itemClickListener: ItemClickListener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
        var view = LayoutInflater.from(context).inflate(R.layout.list_layout, parent, false)
        return Item(view)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
        (holder as Item).bindData(lists[position])

        if(somcondition){
            itemClickListener.itemClick()
        }
    }

    override fun getItemCount(): Int {
        return lists.size;
    }

    internal class Item(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bindData(_list: Employee) {
            itemView.textViewfirstname.text = _list.firstName
            itemView.textViewlastname.text = _list.lastName
        }
    }

    interface ItemClickListener {
        fun itemClick()
    }
}
like image 166
Akshay Raiyani Avatar answered Jan 03 '23 19:01

Akshay Raiyani