2

I am working on an Android app which has a recycler view. I have items ordered randomly in the recycler view. I want to move the fifth item of the list to the first position. And move the item previously at the first position to second position. Can anybody help me with this please?

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Ashish Jha
  • 173
  • 1
  • 3
  • 18

2 Answers2

5

You can use Collections.swap()

  • Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)

METHOD

 public static void swap(List<?> list,
        int i,
        int j)

Parameters:

list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.

SAMPLE CODE

// first swap the item using  Collections.swap() method
Collections.swap(yourList, firstPosition, positionToSwap);

// than notify your adapter about change in list using  notifyItemMoved() method
YourAdapter.notifyItemMoved(firstPosition, positionToSwap);
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
0

The way RecyclerView works is every time a new item comes on screen it calls your custom RecyclerView.Adapter subclass. Adapter has a reference for the dataset you take data for views from and gets passed the ViewHolder (the layout of an item) and index into onBindViewHolder(MyViewHolder holder, int position) to take dataset[position] and put the data into holder.textview.setText(dataset[position]).

As such, to swap places of elements you have 2 options:

  • rearrange data in the initial dataset. Chances are it's an ArrayList<> of some kind and you do TEMP=dataset[5];ArrayList.remove(TEMP);ArrayList.insert(TEMP,1); ArrayList will shift everything as required.

  • if it is important to keep dataset intact, you can rewrite your adapter, so that it keeps a map of { position : dataset_index } and populates items according to that map. That should be trivial.

And then you have to refresh the data with adapter.notifyDataSetChaged();

IcedLance
  • 406
  • 3
  • 12