5

Is there a way to move a specific item to a specific position in RecyclerView using LinearLayoutManager programmatically?

SpaceCore186
  • 586
  • 1
  • 8
  • 20
Anh Phạm
  • 95
  • 1
  • 2
  • 10

1 Answers1

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.
    }
}
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
  • 11
    If 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