这是适配器:

class ToplistAdapter(val context: Context, private val users: MutableList<Toplist>, val itemClick: (Toplist) -> Unit) : RecyclerView.Adapter<ToplistAdapter.ViewHolder>(){

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val user = users[position]
        holder.percent.text = user.prozent
        Picasso.get().load(user.image).into(holder.imagee)

        holder.bind(users[position], context)
    }

    override fun getItemCount() = users.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.toplist, parent, false)
        return ViewHolder(view, itemClick)
    }

    class ViewHolder(itemView: View?, val itemClick: (Toplist) -> Unit) : RecyclerView.ViewHolder(itemView!!){

        val percent = itemView!!.text_percent
        val imagee = itemView!!.image_view

        fun bind(toplist: Toplist, context: Context){
            itemView.setOnClickListener {
                itemClick(toplist)
            }
        }
    }
}


这是片段:

            adapter = ToplistAdapter(activity!!, users) {
                // Profile(it.userid.toString())
            }

            recyclerView.adapter = adapter

            recyclerView.layoutManager = GridLayoutManager(activity!!, 2)
            recyclerView.setHasFixedSize(true)


我知道如何在onBindViewHolder中设置onClicklistener并找出是否单击了text_percentimage_view,但是除了获取userid等之外,如何在片段中进行此操作?

提前致谢

编辑:

请求的数据模型类:

data class Toplist(
        val image: String,
        val prozent: String,
        val userid: Long
)

最佳答案

在您的适配器中创建ClickListener

   open interface ClickListener {
        fun onClick(position: Int)

    }


然后实现你的适配器

class ToplistAdapter(val context: Context, private val users: MutableList<Toplist>, val listener: ClickListener) : RecyclerView.Adapter<ToplistAdapter.ViewHolder>(){

   companion object {
        var clickListener: ClickListener? = null
    }


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

    clickListener = listener
    val user = users[position]
    holder.percent.text = user.prozent
    Picasso.get().load(user.image).into(holder.imagee)

    holder.bind(users[position], context)
    holder.imagee.setOnClickListener {
        itemClick(users[position])
    }
   holder.imagee.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                if (clickListener != null)
                    clickListener?.onClick(position)
            }
        })



    }


然后您的片段或活动添加

     adapter = ToplistAdapter(activity!!, users, object : ToplistAdapter.ClickListener {
            override fun onClick(position: Int) {
               val user=users[position]
               val userid=user.userid
            }
        })

关于java - Android Kotlin-RecyclerView找出 Activity/fragment 中确切单击了哪个内部项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53076904/

10-08 20:41