RecyclerView android: Getting an item at a particular position
Asked Answered
C

1

5

Is there any way to get an item of the RecyclerView at a particular position outside the adapter. e.g in ListView we could do:

    listView.getItem(position); 

Can we do this with RecyclerView ? and also is the order of provided data list maintained ?

Commissar answered 20/1, 2015 at 3:51 Comment(0)
P
10

You can add your own method to RecyclerView or I would suggest the RecyclerView.Adapter itself.

For instance, for ListView, you have:

@Override
public Object getItem(int position) {
    return listData.get(position);
}

You can add the same thing to your RecylcerView.Adapter or access it another way by adding a simple method to your RecylcerView.Adapter:

public List<Model> getList() {
    return this.mModel;
}

Use it like this:

recyclerView.getAdapter().getList().get(position)
Pikeman answered 20/1, 2015 at 4:11 Comment(2)
Thanks for the answer. I had this method in the adapter but i couldn't access it. I tried casting recyclerView.getAdapter() to my adapter class and now i can access it.Commissar
I would argue that if you do this, you expose the list with a possibility of it getting modified from outside. A better way would be to only expose the element according to the ID like so: return this.mModel.get(id)Low

© 2022 - 2024 — McMap. All rights reserved.