javaandroidlistandroid-recyclerviewadapter

Get recyclerView item from possition


I'm creating a app that contains a recycler view, and the user adds any number of items he wants. Is there a way to get one of these items in any activity according to its position?

On BindViewHolder in adapter:

holder.tvName.setText(list.get(possition).getName);
holder.tvNumber.setText(list.get(possition).getNumber);

Suppose that the list contain 10 items, and I want to get the name in possition three from the list

How I can do it?

I try to get the value without possition and it gets the last value


Solution

  • you can simply define a static field(variable) for item's list. and write a static method in your adapter that takes a position and returns an item by position. note that at first you must initialize the static variable by your list in the adapter.

    For example:

    private static list ArrayList<Item>;
    ...
    //write the below code in the adapter. you can write it in constructor or write it in a setter method that you will write or any else where!
    list = // assign your items list to this variable (initializing and assigning)
    ...
    public static Item getItemByPosition(int position){
            return list.get(position);
    }
    

    use it like below in any activity:

    Item myItem = YourAdapter.getItemByPosition(3);
    String myName = myItem.getName();