How do I get the position selected in a RecyclerView?

前端 未结 13 2475
自闭症患者
自闭症患者 2020-11-27 04:40

I am experimenting with the support library\'s recyclerview and cards. I have a recyclerview of cards. Each card has an \'x\' icon at the top right corner to remove it:

13条回答
  •  难免孤独
    2020-11-27 05:02

    Set your onClickListeners on onBindViewHolder() and you can access the position from there. If you set them in your ViewHolder you won't know what position was clicked unless you also pass the position into the ViewHolder

    EDIT

    As pskink pointed out ViewHolder has a getPosition() so the way you were originally doing it was correct.

    When the view is clicked you can use getPosition() in your ViewHolder and it returns the position

    Update

    getPosition() is now deprecated and replaced with getAdapterPosition()

    Update 2020

    getAdapterPosition() is now deprecated and replaced with getAbsoluteAdapterPosition() or getBindingAdapterPosition()

    Kotlin code:

    override fun onBindViewHolder(holder: MyHolder, position: Int) {
            // - get element from your dataset at this position
            val item = myDataset.get(holder.absoluteAdapterPosition)
        }
    

提交回复
热议问题