效果演示
需求和技术分析
RecyclerView Item拖拽排序::长按RecyclerView的Item或者触摸Item的某个按钮。
RecyclerView Item滑动删除:RecyclerView Item滑动删除:RecyclerView的Item滑动删除。
实现方案与技术
利用ItemTouchHelper绑定RecyclerView、ItemTouchHelper.Callback来实现UI更新,并且实现动态控制是否开启拖拽功能和滑动删除功能。
实现步骤
继承抽象类ItemTouchHelper,并在构造方法传入实现的ItemTouchHelper.Callback。
recyclerView绑定ItemTouchHelper:itemTouchHelper.attachToRecyclerView(recyclerView)。
自定义ItemTouchHelper.Callback的实现接口OnItemTouchCallbackListener,由外部更新RecyclerView的Item。
几个主要的布局
activity_main.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/rv_main"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
这个没啥好说的了吧,就是一个RecyclerView啦。
接下来是RecyclerView的Item的布局item.xml:
android:layout_width="match_parent"
android:layout_height="?android:listPreferredItemHeight"
android:background="?selectableItemBackground">
android:id="@+id/iv_touch"
style="@style/ItemStyle"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:src="@android:drawable/alert_dark_frame" />
android:id="@+id/cb_item_check"
style="@style/ItemStyle"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
android:id="@+id/tv_name"
style="@style/ItemStyle"
android:layout_toEndOf="@id/cb_item_check"
android:layout_toRightOf="@id/cb_item_check" />
android:id="@+id/tv_sex"
style="@style/ItemStyle"
android:layout_marginLeft="@dimen/dp_10"
android:layout_marginStart="@dimen/dp_10"
android:layout_toEndOf="@id/tv_name"
android:layout_toRightOf="@id/tv_name" />
这个也不用解释了