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?
2 Answers
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);

- 67,701
- 16
- 123
- 163
-
1do you know how to save that position, because I have done with `Collections.swap()` this works but doesn't save the position when the app is closed and opened again. – TheCoderGuy Feb 20 '19 at 10:17
-
1The u need to save that position when user close the app somewhere and later when user open the use that saved position – AskNilesh Feb 20 '19 at 10:19
-
How can we save that position as you ansewered ? – TheCoderGuy Jun 03 '19 at 21:39
-
@Spritzig how to u want save the position and which position u want to save – AskNilesh Jun 04 '19 at 03:30
-
I will add a question in SO and will let you know. – TheCoderGuy Jun 04 '19 at 09:19
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();

- 406
- 3
- 12