Android Kotlin-RecyclerView找出活动/片段中确切单击了哪个内部项目

时间:2018-10-31 05:32:16

标签: java android android-recyclerview kotlin

这是适配器:

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
)

1 个答案:

答案 0 :(得分:1)

在适配器中创建ClickListener

while (!found && i < 32)

然后实施您的适配器

   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)
            }
        })



    }