gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:31:13 26 4
gpt4 key购买 nike

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

最佳答案

你可以这样做:

一些 Activity/fragment/任何:

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

关于android - 如何以编程方式更改 RecyclerView 中项目的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33698646/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com