如何以编程方式更改项目在RecyclerView中的位置? [英] How to change position of items in RecyclerView programmatically?

查看:79
本文介绍了如何以编程方式更改项目在RecyclerView中的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您可以执行以下操作:

某些活动/片段/任何内容:

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.
    }
}

这篇关于如何以编程方式更改项目在RecyclerView中的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆