RecyclerView实现拖拽排序效果

效果就是这样,RecyclerView列表可拖拽排序,可删除,可添加;

RecyclerView给我们提供了一个手势器:

ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
  @Override
  public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
   int dragFrlg = 0;
   if (recyclerView.getLayoutManager() instanceof GridLayoutManager){
    dragFrlg = ItemTouchHelper.UP|ItemTouchHelper.DOWN|ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;
   }else if(recyclerView.getLayoutManager() instanceof LinearLayoutManager){
    dragFrlg = ItemTouchHelper.UP|ItemTouchHelper.DOWN;
   }
   return makeMovementFlags(dragFrlg,0);
  } 

  @Override
  public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
   //滑动事件 下面注释的代码,滑动后数据和条目错乱,被舍弃
//   Collections.swap(datas,viewHolder.getAdapterPosition(),target.getAdapterPosition());
//   ap.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition()); 

   //得到当拖拽的viewHolder的Position
   int fromPosition = viewHolder.getAdapterPosition();
   //拿到当前拖拽到的item的viewHolder
   int toPosition = target.getAdapterPosition();
   if (fromPosition < toPosition) {
    for (int i = fromPosition; i < toPosition; i++) {
     Collections.swap(datas, i, i + 1);
    }
   } else {
    for (int i = fromPosition; i > toPosition; i--) {
     Collections.swap(datas, i, i - 1);
    }
   }
   ap.notifyItemMoved(fromPosition, toPosition);
   return true;
  } 

  @Override
  public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
    //侧滑删除可以使用;
  } 

  @Override
  public boolean isLongPressDragEnabled() {
   return true;
  }
  /**
   * 长按选中Item的时候开始调用
   * 长按高亮
   * @param viewHolder
   * @param actionState
   */
  @Override
  public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
   if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
    viewHolder.itemView.setBackgroundColor(Color.RED);
    //获取系统震动服务//震动70毫秒
    Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
    vib.vibrate(70);
   }
   super.onSelectedChanged(viewHolder, actionState);
  } 

  /**
   * 手指松开的时候还原高亮
   * @param recyclerView
   * @param viewHolder
   */
  @Override
  public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
   super.clearView(recyclerView, viewHolder);
   viewHolder.itemView.setBackgroundColor(0);
   ap.notifyDataSetChanged(); //完成拖动后刷新适配器,这样拖动后删除就不会错乱
  }
 }); 

设置给RecyclerView即可:

helper.attachToRecyclerView(rv); 

下面是完整的代码和Xml布局文件:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 private final String TAG = this.getClass().getSimpleName();
 private List<String> d = Arrays.asList(
   "A","B","C","D","E","F","G"
   ,"H","I","J","K","L","M","N"
   ,"O","P","Q","R","S","T"
   ,"U","V","W","X","Y","Z");
 private RecyclerView rv ;
 private Ap<String> ap;
 private List<String> datas;
 private EditText edAdd; 

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  initData();
  rv = findViewById(R.id.rv);
  edAdd =findViewById(R.id.et_add);
  rv.setLayoutManager(new GridLayoutManager(this,3));
//  rv.setLayoutManager(new LinearLayoutManager(this));
  ap = new Ap(this, datas);
  rv.setAdapter(ap);
  helper.attachToRecyclerView(rv);
  findViewById(R.id.tv).setOnClickListener(this);
  findViewById(R.id.tv_add).setOnClickListener(this);
 } 

 private void initData() {
  datas = new ArrayList<>();
//  直接用d操作集合会崩溃,Arrays.asList集合不可增删改;详细可以看我的博客
  for (int i = 0; i < d.size(); i++) {
   datas.add(d.get(i));
  }
 } 

 @Override
 public void onClick(View view) {
  switch (view.getId()){
   case R.id.tv:
    for (int i = 0; i < datas.size(); i++) {
     Log.i(TAG, "onClick: ____"+datas.get(i));
    }
    break;
   case R.id.tv_add:
    ap.add(edAdd.getText().toString().trim());
    edAdd.setText(null);
    break;
  }
 } 

 class Ap<T> extends RecyclerView.Adapter<Ap.Vh>{
  private Context context;
  public List<T> stringList;
  public Ap(Context context, List<T> stringList) {
   this.context = context;
   this.stringList = stringList;
  } 

  @Override
  public Ap.Vh onCreateViewHolder(ViewGroup parent, int viewType) {
   return new Vh(LayoutInflater.from(context).inflate(R.layout.item_rv,null));
  } 

  @Override
  public void onBindViewHolder(Ap.Vh holder, final int position) {
   holder.tv.setText(stringList.get(position).toString());
   holder.iv.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
     remove(position);
    }
   });
  } 

  @Override
  public int getItemCount() {
   return stringList.size();
  } 

  public void add(T item){
   int position = stringList.size();
   stringList.add(item);
   notifyItemInserted(position);
  } 

  public void add(int position,T item){
   stringList.add(position,item);
   notifyItemInserted(position);
  }
//  public void remove(T item) {
//   final int position = stringList.indexOf(item);
//   if (-1 == position)
//    return;
//   stringList.remove(item);
//   notifyItemRemoved(position);
//  } 

  public void remove(int position) {
   stringList.remove(position);
   notifyItemRemoved(position);
   notifyItemRangeChanged(position,stringList.size());
  } 

  class Vh extends RecyclerView.ViewHolder { 

   public Vh(View itemView) {
    super(itemView);
    tv = itemView.findViewById(R.id.tv);
    iv = itemView.findViewById(R.id.iv_delete);
   }
   public TextView tv;
   public ImageView iv;
  }
 } 

 ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
  @Override
  public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
   int dragFrlg = 0;
   if (recyclerView.getLayoutManager() instanceof GridLayoutManager){
    dragFrlg = ItemTouchHelper.UP|ItemTouchHelper.DOWN|ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;
   }else if(recyclerView.getLayoutManager() instanceof LinearLayoutManager){
    dragFrlg = ItemTouchHelper.UP|ItemTouchHelper.DOWN;
   }
   return makeMovementFlags(dragFrlg,0);
  } 

  @Override
  public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
   //滑动事件 下面注释的代码,滑动后数据和条目错乱,被舍弃
//   Collections.swap(datas,viewHolder.getAdapterPosition(),target.getAdapterPosition());
//   ap.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition()); 

   //得到当拖拽的viewHolder的Position
   int fromPosition = viewHolder.getAdapterPosition();
   //拿到当前拖拽到的item的viewHolder
   int toPosition = target.getAdapterPosition();
   if (fromPosition < toPosition) {
    for (int i = fromPosition; i < toPosition; i++) {
     Collections.swap(datas, i, i + 1);
    }
   } else {
    for (int i = fromPosition; i > toPosition; i--) {
     Collections.swap(datas, i, i - 1);
    }
   }
   ap.notifyItemMoved(fromPosition, toPosition);
   return true;
  } 

  @Override
  public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
    //侧滑删除可以使用;
  } 

  @Override
  public boolean isLongPressDragEnabled() {
   return true;
  }
  /**
   * 长按选中Item的时候开始调用
   * 长按高亮
   * @param viewHolder
   * @param actionState
   */
  @Override
  public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
   if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
    viewHolder.itemView.setBackgroundColor(Color.RED);
    //获取系统震动服务//震动70毫秒
    Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
    vib.vibrate(70);
   }
   super.onSelectedChanged(viewHolder, actionState);
  } 

  /**
   * 手指松开的时候还原高亮
   * @param recyclerView
   * @param viewHolder
   */
  @Override
  public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
   super.clearView(recyclerView, viewHolder);
   viewHolder.itemView.setBackgroundColor(0);
   ap.notifyDataSetChanged(); //完成拖动后刷新适配器,这样拖动后删除就不会错乱
  }
 });
}

Xml布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
 tools:context="com.ccb.pactera.dragrecyclerviewdemo.MainActivity"> 

 <LinearLayout
  android:id="@+id/ll"
  android:background="#eeeeee"
  android:orientation="horizontal"
  android:layout_width="match_parent"
  android:layout_height="48dp">
  <TextView
   android:layout_width="0dp"
   android:layout_weight="1"
   android:layout_height="48dp"
   android:id="@+id/tv"
   android:text="查看数据"
   android:textColor="#fff"
   android:textSize="16dp"
   android:gravity="center"
   android:background="@color/colorAccent"
   />
  <EditText
   android:id="@+id/et_add"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"/>
  <TextView
   android:layout_width="0dp"
   android:layout_weight="1"
   android:layout_height="48dp"
   android:id="@+id/tv_add"
   android:text="添加数据"
   android:textColor="#fff"
   android:textSize="16dp"
   android:gravity="center"
   android:background="#fc1"
   />
 </LinearLayout>
 <android.support.v7.widget.RecyclerView
  android:id="@+id/rv"
  android:layout_below="@id/ll"
  android:layout_width="match_parent"
  android:layout_height="match_parent" /> 

</RelativeLayout> 

RecyclerView的Item:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:background="#f1f1f1"
 android:layout_height="match_parent">
 <RelativeLayout
  android:layout_width="match_parent"
  android:background="#fff"
  android:layout_margin="0.5dp"
  android:layout_height="match_parent">
 <ImageView
  android:layout_width="match_parent"
  android:layout_height="50dp"
  android:src="@mipmap/icon"
  android:id="@+id/iv"
  android:layout_marginTop="10dp"
  />
<TextView
 android:id="@+id/tv"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:textSize="16dp"
 android:layout_below="@id/iv"
 android:gravity="center_horizontal"
 android:layout_marginBottom="10dp"
 />
 <ImageView
  android:layout_width="25dp"
  android:layout_height="25dp"
  android:layout_alignParentRight="true"
  android:src="@mipmap/detele"
  android:id="@+id/iv_delete"
  />
 </RelativeLayout>
</RelativeLayout> 

资源链接Github

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • android的RecyclerView实现拖拽排序和侧滑删除示例

    在平时开发应用的时候,经常会遇到列表排序.滑动删除的需求.如果列表效果采用的是 ListView 的话,需要经过自定义 View 才能实现效果:但是如果采用的是 RecyclerView 的话,系统 API 就已经为我们提供了相应的功能. 接下来,我们就来看一下怎么用系统 API 来实现排序和删除的效果. 创建 ItemTouchHelper 创建一个 ItemTouchHelper 对象,然后其调用 attachToRecyclerView 方法: RecyclerView recyclerV

  • android RecyclerView实现条目Item拖拽排序与滑动删除

    效果演示 需求和技术分析 RecyclerView Item拖拽排序::长按RecyclerView的Item或者触摸Item的某个按钮. RecyclerView Item滑动删除:RecyclerView Item滑动删除:RecyclerView的Item滑动删除. 实现方案与技术 利用ItemTouchHelper绑定RecyclerView.ItemTouchHelper.Callback来实现UI更新,并且实现动态控制是否开启拖拽功能和滑动删除功能. 实现步骤 继承抽象类ItemTo

  • Android recyclerview实现拖拽排序和侧滑删除

    Recyclerview现在基本已经替代Listview了,RecyclerView也越来越好用了  当我们有实现条目的拖拽排序和侧滑删除时  可以直接时候Recyclerview提供的API就可以直接实现了 先贴上主要代码 private void initveiw() { ArrayList<String> items = new ArrayList<>(Arrays.asList("itme1", "item2", "itme

  • RecyclerView实现拖拽排序效果

    效果就是这样,RecyclerView列表可拖拽排序,可删除,可添加: RecyclerView给我们提供了一个手势器: ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() { @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { int drag

  • jQuery拖拽排序插件制作拖拽排序效果(附源码下载)

    使用jquery拖拽排序插件制作拖拽排序效果是一款非常实用的鼠标拖拽布局插件.效果图如下: 效果演示         源码下载 html代码: <h1>水平拖拽</h1> <div class="demo"> <div class="item item1"><span>1</span></div> <div class="item item2"><

  • vue.draggable实现表格拖拽排序效果

    本文实例为大家分享了vue.draggable实现表格拖拽排序效果展示的具体代码,供大家参考,具体内容如下 主要使用vuedraggable和sortablejs两个组件. 1.安装组件 npm install vuedraggable npm install sortablejs 2.引入组件 import draggable from 'vuedraggable'; import Sortable from 'sortablejs'; export default { components:

  • vue实现拖拽排序效果

    本文实例为大家分享了vue实现拖拽排序效果的具体代码,供大家参考,具体内容如下 效果预览 组件 drag.vue <template>   <TransitionGroup name="group-list" tag="ul">     <li       v-for="(item, index) in list"       :key="item.name"       :draggable=&

  • vuedraggable+element ui实现页面控件拖拽排序效果

    项目要实现一些控件的拖拽排序.从而找到了这款vuedraggable控件,供大家参考,具体内容如下 如上图要实现这些控件的拖拽排序 这是拖拽后 由于公司网络的原因,项目没有使用npm,都是使用的引入的js <script type="text/javascript" src="lib/sortable/Sortable.min.js"></script> <script type="text/javascript"

  • 简单的jQuery拖拽排序效果的实现(增强动态)

    增强动态增加Div效果 原来没有新建动作,分析代码后发现很容易增强~~ <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>测试的拖拽功能</title> <style type="text/css">

  • 简单的jquery拖拽排序效果实现代码

    步骤: 1.实现随鼠标移动的效果: 2.初始化一个元素及其坐标: 3.拖拽对象的最后坐标,与元素的坐标 进行计算和判断 来确定 要插入的目标元素: 4.用insertBefore 方法 插入到目标元素的前面 具体代码如下: 复制代码 代码如下: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8&

随机推荐