PhilBlais
PhilBlais

Reputation: 1176

Find RecyclerView row position by looking through a RecyclerView's values

I have a RecyclerView that's populated with content.

One of the values inside that RecyclerView's Holder is a var entity_id: Int.

I would need to loop through the rows of RecyclerView to find a row that contains a specific entity_id, without knowing the adapter position.

In other words, I know that one of my row's entity_id is 23, I need to retrieve the adapterPosition of that row.

Upvotes: 1

Views: 451

Answers (2)

Bharatesh
Bharatesh

Reputation: 9009

Loop through your final items of adapter and match with your condition, if item found then loop's index is your adapter item position.

private fun getPosition(entityId: Int): Int {
    for (i in list.indices) {
        if (list[i].entity_id == entityId) { //match with your id
            return i
        }
    }
    return -1
}

Upvotes: 2

Edhar Khimich
Edhar Khimich

Reputation: 1664

If you need to get only position for 23 value - you can make a callback in your ViewHolder where you will check the value and if it will be 23 -> send a callback with the position of this item.

Here how it looks ->

Your ViewHolder:

 class MyRecyclerViewAdapter(private val callback: (Int) -> Unit) : RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder>() {

   override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
   }

   override fun getItemCount(): Int {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
   }

   override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
   }

 inner class MyViewHolder(v: View) : RecyclerView.ViewHolder(v) {

    fun bind(model: Model) {

        TODO("Some logic")

        if (model.id == 23) {
            callback.invoke(adapterPosition)
        }
     }
   }
 }

Model:

class Model(val id: Int)

Activity:

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    /** Init LayoutManager 
     *  .... 
     * */

    val adapter = MyRecyclerViewAdapter(callback = { position ->
        TODO("Do some logic with your position")
    })
 }

Upvotes: 0

Related Questions