【问题标题】:How to change position of items in RecyclerView programmatically?如何以编程方式更改 RecyclerView 中项目的位置?
【发布时间】:2015-11-13 17:34:39
【问题描述】:

有没有办法以编程方式使用LinearLayoutManager 将特定项目移动到RecyclerView 中的特定位置?

【问题讨论】:

  • 是否可以选择更新数据集?

标签: android android-recyclerview linearlayoutmanager


【解决方案1】:

你可以这样做:

一些 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);

我的适配器:

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

【讨论】:

  • 我怎么能用动画做到这一点?例如,将位置 n 的项目移动到列表顶部?
  • 如果你想要一个只移动元素的动画,你可以使用Collections.swap(this.mListItems, oldIndex, index); notifyItemMoved(oldIndex, newIndex)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-04
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多