Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change position of items in RecyclerView programmatically?

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

like image 582
Anh Phạm Avatar asked Nov 13 '15 17:11

Anh Phạm


Video Answer


1 Answers

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.
    }
}
like image 138
Not Gabriel Avatar answered Oct 10 '22 17:10

Not Gabriel