Is there a way to move a specific item to a specific position in RecyclerView
using LinearLayoutManager
programmatically?
Asked
Active
Viewed 1.7k times
5
![](../../users/profiles/6111697.webp)
SpaceCore186
- 586
- 1
- 8
- 20
![](../../users/profiles/4262037.webp)
Anh Phạm
- 95
- 1
- 2
- 10
-
1Is updating the dataset an option? – Not Gabriel Nov 13 '15 at 18:32
1 Answers
8
You can do this:
Some Activity/Fragment/Whatever:
List<String> dataset = new ArrayList<>();
RecyclerView recyclervSomething;
LinearLayoutManager lManager;
MyAdapter adapter;
//populate dataset, instantiate recyclerview, adapter and layoutmanager
recyclervSomething.setAdapter(adapter);
recyclervSomething.setLayoutManager(lManager);
adapter.setDataset(dataset);
MyAdapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> dataset;
public MyAdapter() {}
//implement required methods, extend viewholder class...
public void setDataset(List<String> dataset) {
this.dataset = dataset;
notifyDataSetChanged();
}
// Swap itemA with itemB
public void swapItems(int itemAIndex, int itemBIndex) {
//make sure to check if dataset is null and if itemA and itemB are valid indexes.
String itemA = dataset.get(itemAIndex);
String itemB = dataset.get(itemBIndex);
dataset.set(itemAIndex, itemB);
dataset.set(itemBIndex, ItemA);
notifyDataSetChanged(); //This will trigger onBindViewHolder method from the adapter.
}
}
![](../../users/profiles/4941145.webp)
Not Gabriel
- 471
- 4
- 13
-
How could I do this with animation ? For example, moving item at position n to top of the list ? – vtproduction Mar 11 '16 at 08:45
-
11If you want an animation for just moving the elements you can use `Collections.swap(this.mListItems, oldIndex, index); notifyItemMoved(oldIndex, newIndex)` – carvaq Apr 20 '16 at 11:28