RecyclerView使用ItemTouchHelper实现横向滑动删除

本文介绍如何在RecyclerView中通过ItemTouchHelper实现横向滑动删除功能,包括普通状态和编辑状态下的移除操作,以及SwipeActionHelper的使用,提供了详细的功能设计和实现步骤。
摘要由CSDN通过智能技术生成

一、目标

实现删除文件夹收藏功能。

  • 普通状态下,通过横向滑动,移除收藏
    在这里插入图片描述

  • 编辑状态下,点击删除图标,再次点击移除按钮,移除收藏
    在这里插入图片描述

二、体验地址

神马笔记最新版本:【神马笔记 版本1.3.0.apk

三、功能设计

我们需要在普通状态和编辑状态下,均可以移除文件夹收藏。

  • 普通状态下的移除过程
    1. 从右向左滑动,移除按钮从右侧进入;
    2. 继续滑动,移除按钮固定在右侧;
    3. 继续滑动距离超过0.8,移除按钮移动到左侧,同时自动向左侧滑动一段距离,提醒用户松开即可移除;
  • 编辑状态下的移除过程
    1. 点击左侧删除按钮;
    2. 移除按钮从右侧进入;
    3. 点击移除按钮,移除文件夹收藏

四、准备工作

1. ItemTouchHelper

参考《RecyclerView使用ItemTouchHelper实现拖拽排序》一文,介绍了如何使用ItemTouchHelper以及通过实现ItemTouchHelper.Callback实现侧滑删除功能。

2. SwipeActionHelper

因为ItemTouchHelper是对ViewHolderitemView设置translationX实现滑动。

这样会导致列表项控件整体移动,因此,需要做一些定制才能完成功能设计。

这里,使用了SwipeActionHelper来完成这个工作。

你可以在WhatsAndroid项目中找到这份代码。

GitHub项目地址:https://github.com/jicanghai37927/WhatsAndroid

  • SwipeActionHelper.Adapter
public interface Adapter {
   

    boolean isSwiped(SwipeActionHelper helper);

    Adapter getActive(SwipeActionHelper helper);

    int getDirection(SwipeActionHelper helper);

    View getSwipeView(SwipeActionHelper helper);

    List<View> getTouchable(SwipeActionHelper helper);

    void clear(SwipeActionHelper helper);

    void onBegin(SwipeActionHelper helper);

    void onMove(SwipeActionHelper helper, float deltaX);

    void onEnd(SwipeActionHelper helper, float velocityX);

    void onDraw(SwipeActionHelper helper, Canvas canvas);

    void onDrawOver(SwipeActionHelper helper, Canvas canvas);

    void onActionBegin(SwipeActionHelper helper, int action);

    void onActionEnd(SwipeActionHelper helper, int action);

    void onClear(SwipeActionHelper helper, int direction);
}

子类ViewHolder需要实现Adapter接口,完成SwipeActionHelperViewHolder之间的通信。

  • SwipeViewHolder
public abstract class SwipeViewHolder<T> extends BridgeViewHolder<T> implements SwipeActionHelper.Adapter, MarginDividerDecoration.Adapter {
   
    
}

提供了SwipeActionHelper.Adapter的实现。

  • SwipeHolder
public class SwipeHolder {
   

    View container;
    View swipeView;

    boolean isDrag;

    SwipeRunner activeRunner;
    ArrayList<SwipeRunner> list;

    Rect bounds = new Rect();
    SwipeActionHelper helper;
    
}

横向滑动的容器。

  • SwipeRunner

定义了具体的滑动功能,目前支持5种滑动模式。

SwipeRunner子类 滑动行为
DeleteRunner 支持右侧删除按钮
RightDeleteRunner 支持右侧删除及菜单
RightActionRunner 支持右侧菜单
SnapRightRunner 支持按钮吸附在右侧
SnapLeftRunner 支持按钮吸附在左侧

五、组合起来

1. 定义布局资源

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
        xmlns:android="http://schemas.android.com/apk/r
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值