当前位置: 移动技术网 > IT编程>移动开发>Android > Android中RecyclerView实现滑动删除与拖拽功能

Android中RecyclerView实现滑动删除与拖拽功能

2019年07月24日  | 移动技术网IT编程  | 我要评论

碧落黄泉经,烂赌夫斗烂赌妻片尾曲,现在的黄金多少钱一克

前言

从android 5.0开始,谷歌推出了新的控件recyclerview,相对于早它之前的listview,优点多多,功能强大,也给我们的开发着提供了极大的便利,今天自己学习一下recyclerview轻松实现滑动删除及拖拽的效果。

如下图。


相信研究过recyclerview的同学,应该很清楚该怎么实现这样的效果,若是用listview,这样的效果实现起来可能就有点麻烦,但是在强大的recyclerview面前这样的的效果只需很少的代码,因为谷歌给我们提供了强大的工具类itemtouchhelper,它已经处理了关于recyclerview拖动和滑动的实现,并且我们可以在其中实现我们自己的动画,以及定制我们想要的效果。

itemtouchhelper.callback

itemtouchhelper.callback有几个重要的抽象方法,我们继承该抽象类,并重写抽象方法。它是我们实现滑动和拖拽重要的回调。

int getmovementflags(recyclerview recyclerview, recyclerview.viewholder viewholder)

该方法返回一个整数,用来指定拖拽和滑动在哪个方向是被允许的。在其中使用makemovementflags(int dragflags, int swipeflags)返回,该方法第一个参数用来指定拖动,第二个参数用来指定滑动。对于方向参数有6种

itemtouchhelper.up //滑动拖拽向上方向
itemtouchhelper.down//向下
itemtouchhelper.left//向左
itemtouchhelper.right//向右
itemtouchhelper.start//依赖布局方向的水平开始方向
itemtouchhelper.end//依赖布局方向的水平结束方向
boolean onmove(recyclerview recyclerview, recyclerview.viewholder viewholder, recyclerview.viewholder target)

onmove方法是拖拽的回调,参数viewholder是拖动的item,target是拖动的目标位置的item,该方法如果返回true表示切换了位置,反之返回false。

void onswiped(recyclerview.viewholder viewholder, int direction)

onswiped方法为item滑动回调,viewholder为滑动的item,direction为滑动的方向。

上面三个方法是必须重写的方法,当然还有其它一些可供选择的方法。

 /**
  * item是否支持长按拖动
  *
  * @return
  *   true 支持长按操作
  *   false 不支持长按操作
  */
boolean islongpressdragenabled()

 /**
  * item是否支持滑动
  *
  * @return
  *   true 支持滑动操作
  *   false 不支持滑动操作
  */
boolean isitemviewswipeenabled()

 /**
  * 移动过程中绘制item
  *
  * @param c
  * @param recyclerview
  * @param viewholder
  * @param dx
  *   x轴移动的距离
  * @param dy
  *   y轴移动的距离
  * @param actionstate
  *   当前item的状态
  * @param iscurrentlyactive
  *   如果当前被用户操作为true,反之为false
  */
onchilddraw(canvas c, recyclerview recyclerview, recyclerview.viewholder viewholder, float dx, float dy, int actionstate, boolean iscurrentlyactive)

需要注意的是,如果我们想实现拖动或者滑动必须将上面是否支持拖动或者滑动的方法返回true,否则onmove或者onswiped方法不会执行。

功能实现

  adapter=new customadapter(getactivity(),strings);
  recycleview.setadapter(adapter);
  itemtouchhelper.callback callback=new recycleitemtouchhelper(adapter);
  itemtouchhelper itemtouchhelper=new itemtouchhelper(callback);
  itemtouchhelper.attachtorecyclerview(recycleview);

对于itemtouchhelper 构造方法接收一个itemtouchhelper.callback参数,而这个callback就是我们在在上述讲到的工具类,初始化itemtouchhelper 后通过其attachtorecyclerview(@nullable recyclerview recyclerview)方法将我们实现的itemtouchhelper.callback和recyclerview关联,最终达到我们的效果,代码看起来是不是很简单,接下来我们看下我们自定义的callback。

package com.example.xh.adapter;

import android.content.res.resources;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.graphics.canvas;
import android.graphics.paint;
import android.graphics.rect;
import android.support.v7.widget.recyclerview;
import android.support.v7.widget.helper.itemtouchhelper;
import android.util.log;
import android.view.view;

import com.example.xh.r;
import com.example.xh.utils.myapplication;

/**
 * created by xiehui on 2017/2/23.
 */
public class recycleitemtouchhelper extends itemtouchhelper.callback{
 private static final string tag ="recycleitemtouchhelper" ;
 private final itemtouchhelpercallback helpercallback;

 public recycleitemtouchhelper(itemtouchhelpercallback helpercallback) {
  this.helpercallback = helpercallback;
 }

 /**
  * 设置滑动类型标记
  *
  * @param recyclerview
  * @param viewholder
  * @return
  *   返回一个整数类型的标识,用于判断item那种移动行为是允许的
  */
 @override
 public int getmovementflags(recyclerview recyclerview, recyclerview.viewholder viewholder) {
  log.e(tag, "getmovementflags: " );
  //start 右向左 end左向右 left 向左 right向右 up向上
  //如果某个值传0,表示不触发该操作,次数设置支持上下拖拽,支持向右滑动
  return makemovementflags(itemtouchhelper.up|itemtouchhelper.down,itemtouchhelper.end );
 }
 /**
  * item是否支持长按拖动
  *
  * @return
  *   true 支持长按操作
  *   false 不支持长按操作
  */
 @override
 public boolean islongpressdragenabled() {
  return super.islongpressdragenabled();
 }
 /**
  * item是否支持滑动
  *
  * @return
  *   true 支持滑动操作
  *   false 不支持滑动操作
  */
 @override
 public boolean isitemviewswipeenabled() {
  return super.isitemviewswipeenabled();
 }
 /**
  * 拖拽切换item的回调
  *
  * @param recyclerview
  * @param viewholder
  * @param target
  * @return
  *   如果item切换了位置,返回true;反之,返回false
  */
 @override
 public boolean onmove(recyclerview recyclerview, recyclerview.viewholder viewholder, recyclerview.viewholder target) {
  log.e(tag, "onmove: " );
  helpercallback.onmove(viewholder.getadapterposition(),target.getadapterposition());
  return true;
 }
 /**
  * 滑动item
  *
  * @param viewholder
  * @param direction
  *   item滑动的方向
  */
 @override
 public void onswiped(recyclerview.viewholder viewholder, int direction) {
  log.e(tag, "onswiped: ");
  helpercallback.onitemdelete(viewholder.getadapterposition());
 }
 /**
  * item被选中时候回调
  *
  * @param viewholder
  * @param actionstate
  *   当前item的状态
  *   itemtouchhelper.action_state_idle 闲置状态
  *   itemtouchhelper.action_state_swipe 滑动中状态
  *   itemtouchhelper#action_state_drag 拖拽中状态
  */
 @override
 public void onselectedchanged(recyclerview.viewholder viewholder, int actionstate) {
  super.onselectedchanged(viewholder, actionstate);
 }
 public interface itemtouchhelpercallback{
  void onitemdelete(int positon);
  void onmove(int fromposition,int toposition);
 }
}

在默认情况下是支持拖动和滑动的,也就是islongpressdragenabled()isitemviewswipeenabled()是返回true的。在该类中我们创建了一个接口itemtouchhelpercallback并创建两个抽象方法,分别表示拖拽和滑动。在onmove方法中回调创建我们创建的接口方法接口onmove(int fromposition,int toposition) ,并将拖拽和 item 的posion和目标posion传入,posion通过viewholder的getadapterposition()获得,然后在滑动回调方法onswiped中回调onitemdelete(int positon) 。到这里我们自定义的itemtouchhelper.callback创建完成。

上面完成后我们只需要在我们自定义的adapter中实现recycleitemtouchhelper.itemtouchhelpercallback接口,然后在回调方法中更新界面,如下apdater中回调方法实现。

 @override
 public void onitemdelete(int positon) {
  list.remove(positon);
  notifyitemremoved(positon);
 }

 @override
 public void onmove(int fromposition, int toposition) {
  collections.swap(list,fromposition,toposition);//交换数据
  notifyitemmoved(fromposition,toposition);
 }

我们在onitemdelete方法中删除对应posion的数据,在onmove方法中通过collections.swap方法交换对应项数据,然后分别调用notifyitemremoved和notifyitemmoved通过适配器更新ui.

好了到这里功能已经实现了,是不是发现代码很少,当然啰嗦的比较多而已。

功能升级

通过上面简单代码的实现,已经可以滑动删除和拖拽了,当然不满足的你可能发现滑动删除的时候没有动画没有背景,但是我想更改下背景并且在滑动的过程会出现一个删除的图标,给用户反馈,让其明白该操作是删除数据的。当然你还会想再删除的过程中增加一个动画。其实实现这个效果也并不是很麻烦,接下来新的方法实现登场。哦,不对,前面提到过的。

onchilddraw(canvas c, recyclerview recyclerview, recyclerview.viewholder viewholder, float dx, float dy, int actionstate, boolean iscurrentlyactive)

该方法就是移动过程中绘制item的回调。我们在actionstate==itemtouchhelper.action_state_swipe时,即为滑动的时候绘制背景和删除图片。

初始化

 /**
  * 移动过程中绘制item
  *
  * @param c
  * @param recyclerview
  * @param viewholder
  * @param dx
  *   x轴移动的距离
  * @param dy
  *   y轴移动的距离
  * @param actionstate
  *   当前item的状态
  * @param iscurrentlyactive
  *   如果当前被用户操作为true,反之为false
  */
 @override
 public void onchilddraw(canvas c, recyclerview recyclerview, recyclerview.viewholder viewholder, float dx, float dy, int actionstate, boolean iscurrentlyactive) {
  //滑动时自己实现背景及图片
  if (actionstate==itemtouchhelper.action_state_swipe){

   //dx大于0时向右滑动,小于0向左滑动
   view itemview=viewholder.itemview;//获取滑动的view
   resources resources= myapplication.getappcontext().getresources();
   bitmap bitmap= bitmapfactory.decoderesource(resources, r.drawable.delete);//获取删除指示的背景图片
   int padding =10;//图片绘制的padding
   int maxdrawwidth=2*padding+bitmap.getwidth();//最大的绘制宽度
   paint paint=new paint();
   paint.setcolor(resources.getcolor(r.color.btninvalid));
   int x=math.round(math.abs(dx));
   int drawwidth=math.min(x,maxdrawwidth);//实际的绘制宽度,取实时滑动距离x和最大绘制距离maxdrawwidth最小值
   int itemtop=itemview.getbottom()-itemview.getheight();//绘制的top位置
   //向右滑动
   if(dx>0){
    //根据滑动实时绘制一个背景
    c.drawrect(itemview.getleft(),itemtop,drawwidth,itemview.getbottom(),paint);
    //在背景上面绘制图片
    if (x>padding){//滑动距离大于padding时开始绘制图片
     //指定图片绘制的位置
     rect rect=new rect();//画图的位置
     rect.left=itemview.getleft()+padding;
     rect.top=itemtop+(itemview.getbottom()-itemtop-bitmap.getheight())/2;//图片居中
     int maxright=rect.left+bitmap.getwidth();
     rect.right=math.min(x,maxright);
     rect.bottom=rect.top+bitmap.getheight();
     //指定图片的绘制区域
     rect rect1=null;
     if (x<maxright){
      rect1=new rect();//不能再外面初始化,否则dx大于画图区域时,删除图片不显示
      rect1.left=0;
      rect1.top = 0;
      rect1.bottom=bitmap.getheight();
      rect1.right=x-padding;
     }
     c.drawbitmap(bitmap,rect1,rect,paint);
    }
    //绘制时需调用平移动画,否则滑动看不到反馈
    itemview.settranslationx(dx);
   }else {
    //如果在getmovementflags指定了向左滑动(itemtouchhelper。start)时则绘制工作可参考向右的滑动绘制,也可直接使用下面语句交友系统自己处理
    super.onchilddraw(c, recyclerview, viewholder, dx, dy, actionstate, iscurrentlyactive);
   }
  }else {
   //拖动时有系统自己完成
   super.onchilddraw(c, recyclerview, viewholder, dx, dy, actionstate, iscurrentlyactive);
  }
 }

经过上面的处理,发现此时滑动可以看到我们定制的蓝低的删除背景了,此时可能还有疑问,这样删除是不是很生硬,那就再给它加一个透明度的动画,如下。

    float alpha = 1.0f - math.abs(dx) / (float) itemview.getwidth();
    itemview.setalpha(alpha);

总结

好了,到这里recyclerview实现滑动删除和拖拽功能的已经介绍完毕了。希望本文的内容对各位android开发者们能带来一定的帮助,如有问题欢迎留言指出。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网