概述
RecyclerView除了有强大的列表功能外,自身还带有Item拖拽和滑动功能,对于有这方面需求的开发来讲,可以节省不少时间。
使用
1. 创建RecyclerView
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_drag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
2. 创建ItemView
<androidx.cardview.widget.CardView
android:layout_width="66dp"
android:layout_height="66dp"
app:cardBackgroundColor="#1dd9c4"
app:cardCornerRadius="12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textColor="@color/white"
android:textSize="36sp"
android:textStyle="bold" />
</androidx.cardview.widget.CardView>
3. 创建Adapter
public class DragAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List data = new ArrayList();
private Context context;
public DragAdapter(Context context) {
this.context = context;
initData();
}
/**
* 添加数据
*/
private void initData() {
data.clear();
for (int i = 1; i < 10; i++) {
data.add(i);
}
}
@NonN