真滴牛逼,轻松实现RecyclerView 拖动多选功能

文件选择在我们日常开发中是一个比较常见的功能,分为文件单选和多选,单选比如头像上传,多选比如相册中的多图选择、多文件选择删除等。在Android开发中,系统为我们提供了单选/多选的控件,单选用 RadioButton/ RadioGroup(?),多选则用 CheckBox(☑️)。这些都是比较基础的,相信才入门的应该都会已掌握。

抛开单选不说,今天来说说文件多选,在APP上,多选其实使用起来比较麻烦,我们的一个一个地勾选Checkbox(☑️),如果文件有几十个,是不是非常耗费时间?体验也不好,其实在pc 端是不存在这个问题,在pc 端,我们只需拖动鼠标,就能一下将我们需要选择的多个文件选中。APP是能像pc 一样拖动来实现多选吗?答案是肯定的,今天就为大家介绍一个牛逼的库,drag-select-recyclerview,可以轻松实现recyclerView 拖动多选。

drag-select-recyclerview

github地址: github.com/afollestad/…

如果你使用过google 相册,相信你记得它有一个非常方便的功能,就是选择多张图片的时候,可以在屏幕上拖动手指来完成照片多选。drag-select-recyclerview 就能让你在自己的app中轻松实现这个功能。

DragSelectTouchListener 是这个库的核心类,该库将会处理拖动事件拦截和自动滚动逻辑,当拖动到recyclerView 顶部的时候,列表将继续滚动,反之亦然。

使用的时候,将DragSelectTouchListener attache 到 RecyclerView,它将会处理触摸事件的拦截,然后通过一个receiver 来返回结果和更新UI。

val receiver: DragSelectReceiver = // ...val touchListener = DragSelectTouchListener.create(context, receiver)
复制代码

效果图

如何使用?

添加依赖:

dependencies {

  implementation 'com.afollestad:drag-select-recyclerview:2.4.0'
}
复制代码

receiver代码如下:

class MyReceiver : DragSelectReceiver {

  override fun setSelected(index: Int, selected: Boolean) {
    // do something to mark this index as selected/unselected
    if(selected && !selectedIndices.contains(index)) {
      selectedIndices.add(index)
    } else if(!selected) {
      selectedIndices.remove(index)
    }
  }
  
  override fun isSelected(index: Int): Boolean {
    // return true if this index is currently selected
    return selectedItems.contains(index)
  }
  
  override fun isIndexSelectable(index: Int): Boolean {
    // if you return false, this index can't be used with setIsActive()
    return true
  }

  override fun getItemCount(): Int {
    // return size of your data set
    return 0
  }
}
复制代码

DragSelectReceiver 是一个接口,在实际应用中,我们可以让Adapter 实现DragSelectReceiver,这样,记录选中与未选中就很方便。

结合RecyclerView使用如下:

val recyclerView: RecyclerView = // ...
val receiver: DragSelectReceiver = // ...

val touchListener = DragSelectTouchListener.create(context, receiver)
recyclerView.addOnItemTouchListener(touchListener) // important!!

// true for active = true, 0 is the initial selected index
touchListener.setIsActive(true, 0)
复制代码

通过设置setIsActive ,当用户长按列表Item时,触发事件开始拖动选择。

更多使用方法请看Github,或者运行Demo查看。

是不是很酷?赶快引入自己的项目试试吧!

转载于:https://juejin.im/post/5d248facf265da1ba328ec3a

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值