我想在recyclervIEw项目上实现onClickListener.这是我的CustomAdapter.kt代码.
package com.png.kotlinsample/** * Created by admin on 13-08-2017. */import androID.support.v7.Widget.RecyclerVIEwimport androID.vIEw.LayoutInflaterimport androID.vIEw.VIEwimport androID.vIEw.VIEwGroupimport androID.Widget.TextVIEw/** * Created by prashant on 6/19/2017. */class CustomAdapter(val userList: ArrayList<User>, val Listener: (User) -> Unit) : RecyclerVIEw.Adapter<CustomAdapter.VIEwHolder>() { //this method is returning the vIEw for each item in the List class MyAdapter(val userList: ArrayList<User>) overrIDe fun onCreateVIEwHolder(parent: VIEwGroup, vIEwType: Int): CustomAdapter.VIEwHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.row_layout, parent, false) return VIEwHolder(v) } //this method is binding the data on the List overrIDe fun onBindVIEwHolder(holder: CustomAdapter.VIEwHolder, position: Int) { holder.bindItems(userList[position],Listener) } //this method is giving the size of the List overrIDe fun getItemCount(): Int { return userList.size } //the class is hodling the List vIEw class VIEwHolder(itemVIEw: VIEw) : RecyclerVIEw.VIEwHolder(itemVIEw) { fun bindItems(user: User, Listener: (User) -> Unit) = with(itemVIEw) { val textVIEwname = itemVIEw.findVIEwByID(R.ID.textVIEwUsername) as TextVIEw val textVIEwAddress = itemVIEw.findVIEwByID(R.ID.textVIEwAddress) as TextVIEw textVIEwname.text = user.name textVIEwAddress.text = user.address setonClickListener { Listener(user) } } }}
我想从我的活动中点击监听器回调.
解决方法:
class CustomAdapter( val userList: List<User>, val Listener: (User) -> Unit) : RecyclerVIEw.Adapter<CustomAdapter.VIEwHolder>() { overrIDe fun onCreateVIEwHolder(parent: VIEwGroup, vIEwType: Int): CustomAdapter.VIEwHolder = VIEwHolder(LayoutInflater.from(parent.context).inflate(R.layout.row_layout, parent, false)) overrIDe fun onBindVIEwHolder(holder: CustomAdapter.VIEwHolder, position: Int) { holder.bindItems(userList[position]) } overrIDe fun getItemCount(): Int = userList.size inner class VIEwHolder(itemVIEw: VIEw) : RecyclerVIEw.VIEwHolder(itemVIEw) { private val textVIEwname: TextVIEw = itemVIEw.findVIEwByID(R.ID.textVIEwUsername) private val textVIEwAddress: TextVIEw = itemVIEw.findVIEwByID(R.ID.textVIEwAddress) fun bindItems(user: User) = with(itemVIEw) { textVIEwname.text = user.name textVIEwAddress.text = user.address setonClickListener { Listener(user) } } }}
然后
val adapter = CustomAdapter(userList) { user -> // do something with user on click}recyclerVIEw.adapter = adapter
总结 以上是内存溢出为你收集整理的android – 如何在kotlin中的customadpter项目上实现clicklistener?全部内容,希望文章能够帮你解决android – 如何在kotlin中的customadpter项目上实现clicklistener?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)