如何以编程方式更改RecyclerView中项目的位置?

时间:2015-11-13 17:34:40

标签: android android-recyclerview linearlayoutmanager

是否可以通过编程方式使用RecyclerView将特定项目移至LinearLayoutManager中的特定位置?

1 个答案:

答案 0 :(得分:6)

你可以这样做:

一些活动/片段/随便:

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.
    }
}
相关问题