欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中RecyclerView拖拽、侧删功能的实现代码

程序员文章站 2023-12-17 10:53:16
废话不多说,下面展示一下效果。 这是gridview主文件实现。 public class gridviewactivity extends appcomp...

废话不多说,下面展示一下效果。

Android中RecyclerView拖拽、侧删功能的实现代码

这是gridview主文件实现。

public class gridviewactivity extends appcompatactivity {
  recyclerview mrecyclerview;
  list<string> mstringlist;
  recycleradapter mrecyadapter;
  @override
  protected void oncreate(@nullable bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_recyclerview);
    initview();
    initrecy();
  }
  private void initview() {
    getsupportactionbar().setdisplayhomeasupenabled(true);
    mrecyclerview = (recyclerview) findviewbyid(r.id.view_recycler);
  }
  private void initrecy() {
    if (mstringlist == null) {
      mstringlist = new arraylist<>();
    }
    mstringlist.addall(datamanager.getdata(20 - mstringlist.size()));
    mrecyadapter = new recycleradapter(r.layout.item_gridview, mstringlist, true);
    mrecyclerview.setlayoutmanager(new gridlayoutmanager(this, 4));
    mrecyclerview.additemdecoration(new dividergriitemdecoration(this));
    mrecyclerview.sethasfixedsize(true);
    recyitemtouchhelpercallback itemtouchhelpercallback = new recyitemtouchhelpercallback(mrecyadapter, false, true);
    final itemtouchhelper itemtouchhelper = new itemtouchhelper(itemtouchhelpercallback);
    itemtouchhelper.attachtorecyclerview(mrecyclerview);
    mrecyclerview.addonitemtouchlistener(new onrecycleritemclicklistener(mrecyclerview) {
      @override
      public void onitemclick(recyclerview.viewholder viewholder) {
        recycleradapter.viewholder viewholder1 = (recycleradapter.viewholder) viewholder;
        string tvstring = viewholder1.mtextview.gettext().tostring();
        toast.maketext(gridviewactivity.this, "碰了一下 " + tvstring, toast.length_short).show();
      }
      @override
      public void onlongclick(recyclerview.viewholder viewholder) {
        recycleradapter.viewholder viewholder1 = (recycleradapter.viewholder) viewholder;
        string tvstring = viewholder1.mtextview.gettext().tostring();
        toast.maketext(gridviewactivity.this, "长按不放可以拖动!", toast.length_short).show();
        if (viewholder.getlayoutposition() != 0) {
          itemtouchhelper.startdrag(viewholder);
        }
      }
    });
    mrecyclerview.setadapter(mrecyadapter);
  }
  @override
  public boolean onoptionsitemselected(menuitem item) {
    if (item.getitemid() == android.r.id.home) {
      finish();
    }
    return super.onoptionsitemselected(item);
  }
}

代码不难理解,就是activity里面设置一大堆初始化的东西。recyclerview 初始化,setlayoutmanager、additemdecoration、sethasfixedsize、itemtouchhelper、addonitemtouchlistener、setadapter。拖拽效果关键代码是itemtouchhelper.startdrag(viewholder)。其他都围绕着它来转。

然后具体看看各个设置。

datamanager

public class datamanager {
  private static list<string> sstringlist = arrays.aslist("语文", "数学", "英语", "政治",
      "历史", "化学", "生物", "地理", "体育", "音乐");
  public static final list<string> getdata(int number) {
    list<string> stringlist = new arraylist<>();
    for (int i = 0; i < number; i++) {
      stringlist.add(sstringlist.get(i % sstringlist.size()));
    }
    return stringlist;
  }
}

dividergriitemdecoration 这个绘画了item的边线

public class dividergriitemdecoration extends recyclerview.itemdecoration {
  private static final int[] attrs = new int[]{android.r.attr.listdivider};
  private drawable mdivider;
  private int linewidth = 1;
  public dividergriitemdecoration(gridviewactivity gridviewactivity) {
    final typedarray array = gridviewactivity.obtainstyledattributes(attrs);
    mdivider = array.getdrawable(0);
    array.recycle();
  }
  public dividergriitemdecoration(int color) {
    mdivider = new colordrawable(color);
  }
  @override
  public void ondraw(canvas c, recyclerview parent, recyclerview.state state) {
    drawhorizontal(c, parent);
    drawvertical(c, parent);
  }
  private void drawhorizontal(canvas c, recyclerview parent) {
    int childcount = parent.getchildcount();
    for (int i = 0; i < childcount; i++) {
      final view child = parent.getchildat(i);
      final recyclerview.layoutparams params = (recyclerview.layoutparams) child.getlayoutparams();
      final int left = child.getleft() - params.leftmargin;
      final int right = child.getright() + params.rightmargin + linewidth;
      final int top = child.getbottom() + params.bottommargin;
      final int bottom = top + linewidth;
      mdivider.setbounds(left, top, right, bottom);
      mdivider.draw(c);
    }
  }
  private void drawvertical(canvas c, recyclerview parent) {
    final int childcount = parent.getchildcount();
    for (int i = 0; i < childcount; i++) {
      final view child = parent.getchildat(i);
      final recyclerview.layoutparams params = (recyclerview.layoutparams) child.getlayoutparams();
      final int top = child.gettop() - params.topmargin;
      final int bottom = child.getbottom() + params.bottommargin;
      final int left = child.getright() + params.rightmargin;
      final int right = left + linewidth;
      mdivider.setbounds(left, top, right, bottom);
      mdivider.draw(c);
    }
  }
  @override
  public void getitemoffsets(rect outrect, view view, recyclerview parent, recyclerview.state state) {
    outrect.set(0, 0, linewidth, linewidth);
  }
}

recycleradapter 适配器,和ui建立连接

public class recycleradapter extends recyclerview.adapter<recycleradapter.viewholder> {
  private int item_layout;
  private list<string> mdatalist;
  private list<integer> mints;
  private boolean isfirstspecial;
  public recycleradapter(int item_gridview, list<string> datalist, boolean isfisrtspecial) {
    this(item_gridview, datalist);
    this.isfirstspecial = isfisrtspecial;
  }
  public recycleradapter(int item_gridview, list<string> datalist) {
    this.item_layout = item_gridview;
    this.mdatalist = datalist;
    mints = arrays.aslist(r.mipmap.ic_launcher, r.mipmap.ic_launcher,
        r.mipmap.ic_launcher, r.mipmap.ic_launcher,
        r.mipmap.ic_launcher, r.mipmap.ic_launcher);
  }
  @override
  public viewholder oncreateviewholder(viewgroup parent, int viewtype) {
    view view = layoutinflater.from(parent.getcontext()).inflate(item_layout, parent, false);
    return new viewholder(view);
  }
  @override
  public void onbindviewholder(viewholder holder, int position) {
    string str = mdatalist.get(position);
    if (isfirstspecial && position == 0) {
      holder.itemview.setbackgroundcolor(color.ltgray);
      holder.mtextview.settext("不许动");
      holder.mimageview.setimageresource(r.mipmap.ic_launcher);
    } else {
      holder.itemview.setbackgroundcolor(color.white);
      holder.mtextview.settext(str);
      holder.mimageview.setimageresource(mints.get(position % mints.size()));
    }
  }
  @override
  public int getitemcount() {
    return mdatalist == null ? 0 : mdatalist.size();
  }
  public list<string> getdatalist() {
    return mdatalist;
  }
  class viewholder extends recyclerview.viewholder {
    textview mtextview;
    imageview mimageview;
    public viewholder(view itemview) {
      super(itemview);
      mtextview = itemview.findviewbyid(r.id.tv_item);
      mimageview = itemview.findviewbyid(r.id.img_item);
    }
  }
}

onrecycleritemclicklistener,点击事件 。我们借用手势工具类gesturedetectorcompat 来操作

public abstract class onrecycleritemclicklistener implements recyclerview.onitemtouchlistener{
  private gesturedetectorcompat mgesturedetectorcompat;
  private recyclerview mrecyclerview;
  public onrecycleritemclicklistener(recyclerview mrecyclerview) {
    this.mrecyclerview = mrecyclerview;
    mgesturedetectorcompat = new gesturedetectorcompat(mrecyclerview.getcontext(),
        new itemtouchhelpergesturelistener());
  }
  @override
  public boolean onintercepttouchevent(recyclerview rv, motionevent e) {
    mgesturedetectorcompat.ontouchevent(e);
    return false;
  }
  @override
  public void ontouchevent(recyclerview rv, motionevent e) {
    mgesturedetectorcompat.ontouchevent(e);
  }
  @override
  public void onrequestdisallowintercepttouchevent(boolean disallowintercept) {
  }
  //回调事件
  public abstract void onitemclick(recyclerview.viewholder viewholder);
  public abstract void onlongclick(recyclerview.viewholder viewholder);
  private class itemtouchhelpergesturelistener extends gesturedetector.simpleongesturelistener {
    @override
    public boolean onsingletapup(motionevent e) {
      view childviewunder = mrecyclerview.findchildviewunder(e.getx(), e.gety());
      if (childviewunder != null) {
        recyclerview.viewholder childviewholder = mrecyclerview.getchildviewholder(childviewunder);
        onitemclick(childviewholder);
      }
      return true;
    }
    @override
    public void onlongpress(motionevent e) {
      view childviewunder = mrecyclerview.findchildviewunder(e.getx(), e.gety());
      if (childviewunder != null) {
        recyclerview.viewholder childviewholder = mrecyclerview.getchildviewholder(childviewunder);
        onlongclick(childviewholder);
      }
    }
  }
}

recyitemtouchhelpercallback

public class recyitemtouchhelpercallback extends itemtouchhelper.callback {
  recyclerview.adapter madapter;
  boolean isswipeenable;
  boolean isfirstdragunable;
  public recyitemtouchhelpercallback(recyclerview.adapter madapter) {
    this.madapter = madapter;
    isswipeenable = true;
    isfirstdragunable = false;
  }
  public recyitemtouchhelpercallback(recyclerview.adapter madapter, boolean isswipeenable, boolean isfirstdragunable) {
    this.madapter = madapter;
    this.isswipeenable = isswipeenable;
    this.isfirstdragunable = isfirstdragunable;
  }
//  获取touch的响应方向
  @override
  public int getmovementflags(recyclerview recyclerview, recyclerview.viewholder viewholder) {
    if (recyclerview.getlayoutmanager() instanceof gridlayoutmanager) {//网格布局时候
      int dragflags = itemtouchhelper.up | itemtouchhelper.down |
          itemtouchhelper.left | itemtouchhelper.right;
      int swipeflags = 0;
      return makemovementflags(dragflags, swipeflags);
    } else {//list布局时候
      int dragflags = itemtouchhelper.up | itemtouchhelper.down;
      int swipeflags = itemtouchhelper.start | itemtouchhelper.end;
      return makemovementflags(dragflags, swipeflags);
    }
  }
  @override
  public boolean onmove(recyclerview recyclerview, recyclerview.viewholder viewholder, recyclerview.viewholder target) {
    int fromposition = viewholder.getadapterposition();
    int toposition = target.getadapterposition();
    if (isfirstdragunable && toposition == 0) {
      return false;
    }
    //重新更新排序
    if (fromposition < toposition) {
      for (int i = fromposition; i < toposition; i++) {
        collections.swap(((recycleradapter) madapter).getdatalist(), i, i + 1);
      }
    } else {
      for (int i = fromposition; i > toposition; i--) {
        collections.swap(((recycleradapter) madapter).getdatalist(), i, i - 1);
      }
    }
    //刷新
    madapter.notifyitemmoved(fromposition, toposition);
    return true;
  }
  /**
   * 侧滑删除后会回调的方法
   */
  @override
  public void onswiped(recyclerview.viewholder viewholder, int direction) {
    int adapterposition = viewholder.getadapterposition();
    madapter.notifyitemremoved(adapterposition);
    ((recycleradapter)madapter).getdatalist().remove(adapterposition);
  }
  @override
  public void onselectedchanged(recyclerview.viewholder viewholder, int actionstate) {
    if (actionstate != itemtouchhelper.action_state_idle) {
      viewholder.itemview.setbackgroundcolor(color.ltgray);
    }
    super.onselectedchanged(viewholder, actionstate);
  }
  @override
  public void clearview(recyclerview recyclerview, recyclerview.viewholder viewholder) {
    super.clearview(recyclerview, viewholder);
    viewholder.itemview.setbackgroundcolor(color.white);
  }
  @override
  public boolean islongpressdragenabled() {
    return !isfirstdragunable;
  }
  @override
  public boolean isitemviewswipeenabled() {
    return isswipeenable;
  }
}

下面是list的相关设置

同样,listview也是一顿初始化设置。

public class listviewactivity extends appcompatactivity {
  recyclerview mrecyclerview;
  list<string> mstringlist;
  recycleradapter mrecyadapter;
  @override
  protected void oncreate(@nullable bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_recyclerview);
    initview();
    initrecy();
  }
  private void initrecy() {
    if (mstringlist == null) {
      mstringlist = new arraylist<>();
    }
    mstringlist.addall(datamanager.getdata(15 - mstringlist.size()));
    mrecyadapter = new recycleradapter(r.layout.item_listview, mstringlist);
    mrecyclerview.setlayoutmanager(new linearlayoutmanager(this));
    mrecyclerview.additemdecoration(new dividerlistitemdecoration(this, linearlayoutmanager.vertical));
    mrecyclerview.sethasfixedsize(true);
    recyitemtouchhelpercallback itemtouchhelpercallback = new recyitemtouchhelpercallback(mrecyadapter);
    final itemtouchhelper itemtouchhelper = new itemtouchhelper(itemtouchhelpercallback);
    itemtouchhelper.attachtorecyclerview(mrecyclerview);
    mrecyclerview.addonitemtouchlistener(new onrecycleritemclicklistener(mrecyclerview) {
      @override
      public void onitemclick(recyclerview.viewholder viewholder) {
        recycleradapter.viewholder viewholder1 = (recycleradapter.viewholder) viewholder;
        string tvstring = viewholder1.mtextview.gettext().tostring();
        toast.maketext(listviewactivity.this, "碰了一下 " + tvstring, toast.length_short).show();
      }
      @override
      public void onlongclick(recyclerview.viewholder viewholder) {
        toast.maketext(listviewactivity.this, "长按不放可以拖动!", toast.length_short).show();
      }
    });
    mrecyclerview.setadapter(mrecyadapter);
  }
  private void initview() {
    getsupportactionbar().setdisplayhomeasupenabled(true);
    mrecyclerview = (recyclerview) findviewbyid(r.id.view_recycler);
  }
  @override
  public boolean onoptionsitemselected(menuitem item) {
    if (item.getitemid() == android.r.id.home) {
      finish();
    }
    return super.onoptionsitemselected(item);
  }
}

dividerlistitemdecoration

public class dividerlistitemdecoration extends recyclerview.itemdecoration {
  private static final int[] attrs = new int[] {android.r.attr.listdivider};
  public static final int horizontal_list = linearlayoutmanager.horizontal;
  public static final int vertical_list = linearlayoutmanager.vertical;
  private drawable mdivider;
  private int morientation;
  public dividerlistitemdecoration() {
    super();
  }
  public dividerlistitemdecoration(context context, int orientation) {
    final typedarray array = context.obtainstyledattributes(attrs);
    mdivider = array.getdrawable(0);
    array.recycle();
    this.morientation = orientation;
  }
  public dividerlistitemdecoration(context context, int orientation, int drawableid) {
    mdivider = contextcompat.getdrawable(context, drawableid);
    setorientation(orientation);
  }
  @override
  public void ondraw(canvas c, recyclerview parent, recyclerview.state state) {
    super.ondraw(c, parent, state);
  }
  @override
  public void ondrawover(canvas c, recyclerview parent, recyclerview.state state) {
    super.ondrawover(c, parent, state);
  }
  @override
  public void getitemoffsets(rect outrect, view view, recyclerview parent, recyclerview.state state) {
    if (morientation == vertical_list) {
      outrect.set(0, 0, 0, mdivider.getintrinsicheight());
    } else {
      outrect.set(0, 0, mdivider.getintrinsicwidth(), 0);
    }
    super.getitemoffsets(outrect, view, parent, state);
  }
  public void setorientation(int orientation) {
    if (orientation != horizontal_list && orientation != vertical_list) {
      throw new illegalargumentexception("invalid orientaion");
    }
    morientation = orientation;
  }
}

源码下载:http://download.csdn.net/download/loongago/9972876

总结

以上所述是小编给大家介绍的android中recyclerview拖拽、侧删功能的实现代码,希望对大家有所帮助

上一篇:

下一篇: