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())
Go to app > java > package name > right-click > New > Kotlin class/file and name that file as CustomAdapter and then click on OK.
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()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With