上次分析源码,我们知道,ItemTouchHelper对被选中的ViewHodler进行动画操作都是通过ItemTouchUIUtilImpl这个类,我们想要实现侧滑删除,必定需要对ViewHodler进行平移操作,ItemTouchHelper.Callback通过onChildDraw方法调用了ItemTouchUIUtilImpl中的方法,所以我们改写onChildDraw方法
@Override
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
if (dY != 0 && dX == 0) {//因为我们只关注侧滑,而侧滑条件是dX!=0&&dY ==0,所以其他的情况调用ItemTouchUIUtilImpl的方法
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
if (iMoveAndSwipeCallback != null) {
iMoveAndSwipeCallback.onChildDraw(viewHolder, dX, dY);
}
}
并实现iMoveAndSwipeCallback的onChildDraw方法
@Override
public void onChildDraw(RecyclerView.ViewHolder viewHolder, float dX, float dY) {
MyAdapter.MyViewHolder myViewHolder = (MyAdapter.MyViewHolder) viewHolder;
//最大偏移不超过删除布局宽度
if (dX < -myViewHolder.ll_remove.getWidth()) {
dX = -myViewHolder.ll_remove.getWidth();
}
myViewHolder.tv.setTranslationX(dX);
}
我们RecyclerView的item的布局文件是这样的
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal">
<LinearLayout
android:id="@+id/ll_remove"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_remove"
android:layout_width="100dp"
android:layout_height="match_parent"
android:background="@android:color/holo_red_light"
android:gravity="center"
android:text="remove"
android:textColor="@android:color/white" />
<TextView
android:id="@+id/tv_cancel"
android:layout_width="100dp"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_bright"
android:gravity="center"
android:text="cancel"
android:textColor="@android:color/white" />
</LinearLayout>
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
android:gravity="center"
android:textColor="@android:color/white" />
</FrameLayout>

item.png
其中删除和取消的布局在下层,好了,我们来看下效果

recyclerview.gif
但是,我们的item并不能获取点击事件,因为ItemTouchHelper并没有把事件传递给子控件,解决方法:把ItemTouchHelper复制到自己的项目中!我们只需要改OnItemTouchListener这个对象就可以了,修改后如下:
private final RecyclerView.OnItemTouchListener mOnItemTouchListener = new RecyclerView.OnItemTouchListener() {
private boolean onClick;
@Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent event) {
mGestureDet