Android使用CardView作为RecyclerView的Item并实现拖拽和左滑删除

Android使用CardView作为RecyclerView的Item并实现拖拽和左滑删除,第1张

概述引言CardView是Android5.0系统之后引入的众多控件之一,实现之后的效果也是比较酷的,它经常被用在RecyclerView和ListView中的Item中。今天我们就来了解一下CardView的属性,然后使用CardView和RecyclerView结合实现

引言

CardVIEw是AndroID 5.0系统之后引入的众多控件之一,实现之后的效果也是比较酷的,它经常被用在RecyclerVIEw和ListVIEw中的Item中。今天我们就来了解一下CardVIEw的属性,然后使用CardVIEw和RecyclerVIEw结合实现一个可以拖拽Item的布局。

CardVIEw的属性

 CardVIEw继承自FrameLayout,所以子控件的布局规则和FrameLayout的一样,是按照层次堆叠的

下面是CardVIEw的一些常用属性:

CardVIEw的基本使用

先看一下效果:

这是一个CardVIEw,多个罗列起来看起啦会更酷,好了,我们先看一下代码:

<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"  xmlns:app="http://schemas.androID.com/apk/res-auto"  androID:orIEntation="vertical" androID:paddingtop="10dp"  androID:layout_wIDth="match_parent" androID:layout_height="wrap_content">   <androID.support.v7.Widget.CardVIEw    androID:layout_wIDth="match_parent" androID:layout_height="60dp"    androID:layout_marginleft="10dp" androID:layout_marginRight="10dp"    app:contentpaddingleft="20dp" app:cardBackgroundcolor="@color/colorPrimary"    app:cardCornerRadius="5dp" app:cardElevation="5dp"    androID:layout_marginBottom="10dp"    app:cardPreventCornerOverlap="true">    <linearLayout      androID:layout_wIDth="match_parent" androID:layout_height="match_parent"      androID:orIEntation="horizontal" androID:gravity="center_vertical">      <!--左侧图片-->      <ImageVIEw        androID:layout_wIDth="50dp" androID:layout_height="50dp"        androID:src="@mipmap/ic_launcher"/>      <linearLayout        androID:layout_wIDth="match_parent" androID:layout_height="match_parent"        androID:orIEntation="vertical" androID:layout_marginleft="10dp"        androID:gravity="center_vertical">        <!--姓名-->        <TextVIEw          androID:ID="@+ID/txt_name" androID:layout_wIDth="wrap_content"          androID:layout_height="wrap_content" androID:textSize="16sp"          androID:textcolor="@androID:color/white" androID:text="王二"/>        <!--描述-->        <TextVIEw          androID:ID="@+ID/txt_describe" androID:layout_wIDth="wrap_content"          androID:layout_height="wrap_content" androID:layout_margintop="5dp"          androID:textSize="12sp" androID:textcolor="@androID:color/darker_gray"          androID:text="一个很厉害的人"/>      </linearLayout>    </linearLayout>  </androID.support.v7.Widget.CardVIEw></linearLayout>

看完了布局文件,是不是觉得这个布局不仅炫酷而且使用简单,下面我们把它应用到RecyclerVIEw中,看起来会更炫酷。

CardVIEw应用在RecyclerVIEw中

CardVIEw通常会应用在RecyclerVIEw和ListVIEw中,今天我们就讲一讲如何应用在RecyclerVIEw中。我们现在在大多数应用或者手机系统界面中会见到这样的效果:

是不是觉得很棒,下面我们就用CardVIEw和RecyclerVIEw来实现一下这个效果。

布局文件

我们实现这个效果的第一步是先添加依赖库:

implementation 'com.androID.support:recyclervIEw-v7:26.+'implementation 'com.androID.support:cardvIEw-v7:26.+'

然后写一下布局文件,Item的布局文件我就直接采用上面的代码了,然后再写一个主界面的布局文件,比较简单,如下:

<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"  xmlns:app="http://schemas.androID.com/apk/res-auto"  xmlns:tools="http://schemas.androID.com/tools"  androID:layout_wIDth="match_parent"  androID:layout_height="match_parent"  androID:orIEntation="vertical" androID:paddingtop="10dp"  tools:context="com.jyx.demo.myapplication.MainActivity">   <androID.support.v7.Widget.RecyclerVIEw    androID:ID="@+ID/my_recyclerVIEw"    androID:layout_wIDth="match_parent"    androID:layout_height="wrap_content"/> </linearLayout>

Activity内代码

public class MainActivity extends AppCompatActivity {  private RecyclerVIEw mRecyclerVIEw;   @OverrIDe  protected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.activity_main);     mRecyclerVIEw = (RecyclerVIEw) findVIEwByID(R.ID.my_recyclerVIEw);    //设置LayoutManager    linearlayoutmanager linearlayoutmanager = new linearlayoutmanager(this);    linearlayoutmanager.setorIEntation(linearlayoutmanager.VERTICAL);    mRecyclerVIEw.setLayoutManager(linearlayoutmanager);     //绑定adapter    MyAdapter myAdapter = new MyAdapter(this);    mRecyclerVIEw.setAdapter(myAdapter);     }  //adapter  class MyAdapter extends RecyclerVIEw.Adapter<MyAdapter.VIEwHolder> {     LayoutInflater mInflater;    List<MData> mList = addData();     public MyAdapter(Context context) {      mInflater = LayoutInflater.from(context);    }     @OverrIDe    public MyAdapter.VIEwHolder onCreateVIEwHolder(VIEwGroup parent,int vIEwType) {      VIEw vIEw = mInflater.inflate(R.layout.item_my_recyclervIEw,parent,false);      VIEwHolder vIEwHolder = new VIEwHolder(vIEw);      return vIEwHolder;    }     @OverrIDe    public voID onBindVIEwHolder(MyAdapter.VIEwHolder holder,int @R_301_4612@) {      holder.mname.setText(mList.get(@R_301_4612@).getUsername());      holder.mDescribe.setText(mList.get(@R_301_4612@).getDescription());    }     @OverrIDe    public int getItemCount() {      return mList.size();    }     public class VIEwHolder extends RecyclerVIEw.VIEwHolder {      private TextVIEw mname;      private TextVIEw mDescribe;      public VIEwHolder(VIEw itemVIEw) {        super(itemVIEw);        mname = itemVIEw.findVIEwByID(R.ID.txt_name);        mDescribe = itemVIEw.findVIEwByID(R.ID.txt_describe);      }    }  }  //制造一个数据源  private class MData{    String username;    String description;     public String getUsername() {      return username;    }     public voID setUsername(String username) {      this.username = username;    }     public String getDescription() {      return description;    }     public voID setDescription(String description) {      this.description = description;    }  }  private List<MData> addData(){    List<MData> List = new ArrayList();     MData mData = new MData();    mData.setUsername("王二");    mData.setDescription("一个很厉害的人");    List.add(mData);     mData = new MData();    mData.setUsername("张三");    mData.setDescription("呵呵");    List.add(mData);     mData = new MData();    mData.setUsername("李四");    mData.setDescription("嘻嘻");    List.add(mData);     mData = new MData();    mData.setUsername("赵一");    mData.setDescription("呵呵");    List.add(mData);     mData = new MData();    mData.setUsername("钱多");    mData.setDescription("地主家的傻儿子");    List.add(mData);    return List;  }}

好了,这就是一个没有任何效果的列表界面,我一看一下效果:

itemtouchhelper

想实现拖拽和滑动删除的效果,很可惜RecyclerVIEw并没有提供现成的API供我们使用,但是SDK为我们提供了itemtouchhelper这样一个工具类帮助我们来轻松实现这些功能,我们先来了解一下itemtouchhelper。官方文档是这样介绍的:

This is a utility class to add swipe to dismiss and drag & drop support to RecyclerVIEw.It works with a RecyclerVIEw and a Callback class,which configures what type of interactions are enabled and also receives events when user performs these actions.Depending on which functionality you support,you should overrIDe onMove(RecyclerVIEw,VIEwHolder,VIEwHolder) and / or onSwiped(VIEwHolder,int).

大致意思就是,这是个工具类,可以实拖拽移动和策划删除,使用这个工具需要RecyclerVIEw和Callback。同时需要重写onMove()和onSwiped()方法。接下来就讲讲如何使用ItemtouchHlper。

1.新建一个接口,并且让Adapter实现

我们选择使用一个接口来实现Adapter和itemtouchhelper之间涉及数据的 *** 作,因为itemtouchhelper完成触摸的各种动画以后,就要对Adapter的数据进行 *** 作,比如我们在侧滑删除以后,最后需要调用Adapter的notifyItemRemove()方法来移除该数据。所以我们可以把数据 *** 作的部分抽象成一个接口方法,让Callbac调用它即可。具体如下:

新建一个接口:

itemtouchhelperAdapter

public interface itemtouchhelperAdapter {  //移动item  public voID onItemmove(int from@R_301_4612@,int to@R_301_4612@);  //删除item  public voID onItemDelete(int @R_301_4612@);}

之后让Adapter实现这个接口

class MyAdapter extends RecyclerVIEw.Adapter<MyAdapter.VIEwHolder> implements itemtouchhelperAdapter{     LayoutInflater mInflater;    List<MData> mList = addData();     public MyAdapter(Context context) {      mInflater = LayoutInflater.from(context);    }     @OverrIDe    public MyAdapter.VIEwHolder onCreateVIEwHolder(VIEwGroup parent,int @R_301_4612@) {      holder.mname.setText(mList.get(@R_301_4612@).getUsername());      holder.mDescribe.setText(mList.get(@R_301_4612@).getDescription());    }     @OverrIDe    public int getItemCount() {      return mList.size();    }     @OverrIDe    public voID onItemmove(int from@R_301_4612@,int to@R_301_4612@) {      //交换位置      Collections.swap(mList,from@R_301_4612@,to@R_301_4612@);      notifyItemmoved(from@R_301_4612@,to@R_301_4612@);    }     @OverrIDe    public voID onItemDelete(int @R_301_4612@) {      //移除数据      mList.remove(@R_301_4612@);      notifyItemRemoved(@R_301_4612@);    }     public class VIEwHolder extends RecyclerVIEw.VIEwHolder {      private TextVIEw mname;      private TextVIEw mDescribe;      public VIEwHolder(VIEw itemVIEw) {        super(itemVIEw);        mname = itemVIEw.findVIEwByID(R.ID.txt_name);        mDescribe = itemVIEw.findVIEwByID(R.ID.txt_describe);      }    }  }

接下来我们直接在Callback中直接调用接口里的方法就可以了。

2.新建Callback方法,继承itemtouchhelper.Callback

官方文档已经告诉我们,使用itemtouchhelper需要一个Callback,这个Callback是itemtouchhelper.Callback的子类,我们需要新建一个类来继承itemtouchhelper.Callback,然后重写一些方法来实现我们的需求。代码如下:

public class myitemtouchhelperCallBack extends itemtouchhelper.Callback{  private itemtouchhelperAdapter itemtouchhelperAdapter;   public myitemtouchhelperCallBack(itemtouchhelperAdapter itemtouchhelperAdapter) {    this.itemtouchhelperAdapter = itemtouchhelperAdapter;  }   @OverrIDe  public int getMovementFlags(RecyclerVIEw recyclerVIEw,RecyclerVIEw.VIEwHolder vIEwHolder) {    //允许上下拖动    int dragFlags = itemtouchhelper.UP | itemtouchhelper.DOWN;    //允许从右向左滑动    int swipeFlags = itemtouchhelper.left;    return makeMovementFlags(dragFlags,swipeFlags);  }   @OverrIDe  public boolean onMove(RecyclerVIEw recyclerVIEw,RecyclerVIEw.VIEwHolder vIEwHolder,RecyclerVIEw.VIEwHolder target) {    //onItemmove接口里的方法    itemtouchhelperAdapter.onItemmove(vIEwHolder.getAdapter@R_301_4612@(),target.getAdapter@R_301_4612@());    return true;  }   @OverrIDe  public voID onSwiped(RecyclerVIEw.VIEwHolder vIEwHolder,int direction) {    //onItemDelete接口里的方法    itemtouchhelperAdapter.onItemDelete(vIEwHolder.getAdapter@R_301_4612@());  }   @OverrIDe  public boolean isLongPressDragEnabled() {    //该方法返回值为true时,表示支持长按ItemVIEw拖动    return true;  }   @OverrIDe  public boolean isItemVIEwSwipeEnabled() {    //该方法返回true时,表示如果用户触摸并且左滑了vIEw,那么可以执行滑动删除 *** 作,就是可以调用onSwiped()方法    return true;  }}

itemtouchhelper.Callback还有其他几个常用方法:

public voID onSelectedChanged(RecyclerVIEw.VIEwHolder vIEwHolder,int actionState):从静止状态变为拖拽或者滑动的时候会调用该方法,参数actionState表示当前状态。 public voID clearVIEw(RecyclerVIEw recyclerVIEw,VIEwHolder vIEwHolder):当用户 *** 作完某个item并且动画也结束后会调用该方法,一般我们在该方法内恢复ItemVIEw的初始状态,防止由于复用而产生的错乱问题。 public voID onChildDraw(…):我们可以在这个方法内实现我们自定义的交互规则或者自定义动画。

这样下来我们就只剩下一步了。

3.为RecyclerVIEw添加itemtouchhelper

代码如下:

  itemtouchhelper.Callback callback = new myitemtouchhelperCallBack(myAdapter);  itemtouchhelper touchHelper = new itemtouchhelper(callback);  touchHelper.attachToRecyclerVIEw(mRecyclerVIEw);

这样,我们就实现了我们的需求,我们一起来看看效果:

好了,我们的需求完成了,效果是不是很炫酷,当然大家可以根据自己的需求做出更炫酷的效果,到时候别忘了与大家一起分享。希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android使用CardView作为RecyclerView的Item并实现拖拽和左滑删除全部内容,希望文章能够帮你解决Android使用CardView作为RecyclerView的Item并实现拖拽和左滑删除所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1143585.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存