两个recycleview拖拽item示例代码
时间: 2023-08-29 21:08:15 浏览: 97
Recyclerview中可以任意拖拽item的demo
以下是一个简单的示例代码,演示如何实现两个RecyclerView之间的拖拽添加item功能:
```java
public class MainActivity extends AppCompatActivity implements ItemTouchHelperAdapter {
private RecyclerView recyclerView1, recyclerView2;
private Adapter1 adapter1;
private Adapter2 adapter2;
private List<String> data1 = new ArrayList<>();
private List<String> data2 = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView1 = findViewById(R.id.recyclerView1);
recyclerView2 = findViewById(R.id.recyclerView2);
// 初始化数据
for (int i = 0; i < 10; i++) {
data1.add("item " + i);
data2.add("item " + (i + 10));
}
// 创建Adapter和LayoutManager
adapter1 = new Adapter1(data1, this);
adapter2 = new Adapter2(data2, this);
LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
recyclerView1.setLayoutManager(layoutManager1);
recyclerView2.setLayoutManager(layoutManager2);
recyclerView1.setAdapter(adapter1);
recyclerView2.setAdapter(adapter2);
// 创建ItemTouchHelper
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(this);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(recyclerView1);
itemTouchHelper.attachToRecyclerView(recyclerView2);
}
// 实现ItemTouchHelperAdapter接口
@Override
public void onItemMove(int fromPosition, int toPosition) {
// 根据拖拽的位置,将数据从一个RecyclerView的Adapter中删除,添加到另一个RecyclerView的Adapter中
if (fromPosition < data1.size()) {
String item = data1.remove(fromPosition);
data2.add(toPosition, item);
adapter1.notifyItemRemoved(fromPosition);
adapter2.notifyItemInserted(toPosition);
} else {
String item = data2.remove(fromPosition - data1.size());
data1.add(toPosition, item);
adapter2.notifyItemRemoved(fromPosition - data1.size());
adapter1.notifyItemInserted(toPosition);
}
}
@Override
public void onItemDismiss(int position) {
// 根据删除的位置,从另一个RecyclerView的Adapter中删除对应的数据
if (position < data1.size()) {
data2.remove(position);
adapter2.notifyItemRemoved(position);
} else {
data1.remove(position - data1.size());
adapter1.notifyItemRemoved(position - data1.size());
}
}
}
```
在上述代码中,Adapter1和Adapter2分别是两个RecyclerView的Adapter,SimpleItemTouchHelperCallback是ItemTouchHelper的一个回调类,用于实现拖拽和删除item的功能。实现的拖拽添加item的方法在MainActivity中的onItemMove()方法中,根据拖拽的位置,将数据从一个RecyclerView的Adapter中删除,添加到另一个RecyclerView的Adapter中。删除item的方法在MainActivity中的onItemDismiss()方法中,根据删除的位置,从另一个RecyclerView的Adapter中删除对应的数据。
阅读全文