赞
踩
效果图:
实现步骤:
1.新建一个类继承 ItemTouchHelper.Callback:
class ItemDrag extends ItemTouchHelper.Callback{ //设置可移动的标志,我用的GridLayout,所有可移动标志为up,down,left,right. 如果是LinerLayout,就是up,down. @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { int dragFlags = ItemTouchHelper.UP|ItemTouchHelper.DOWN |ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT; int swipeFlags = 0; return makeMovementFlags(dragFlags,swipeFlags); } //移动时会触发这个方法 @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { int fromPosition = viewHolder.getAdapterPosition(); //取得第一个item的position int toPosition = target.getAdapterPosition(); //取得目标item的position Collections.swap(mChoosed,fromPosition,toPosition); //mChoosed是Recylerview的data集合,将两个item交换 mChoosedTagAdapter.notifyItemMoved(fromPosition,toPosition); //recylerview的adapter通知交换更新 return true; } @Override public boolean isLongPressDragEnabled() { //设置是否开启长按可拖拉 mShowIcon = true; mTagAdapter.notifyDataSetChanged(); mChoosedTagAdapter.notifyDataSetChanged(); mButton.setText("完成"); return true; } @Override //移动完成后的回调 public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { } @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(0); } }
2.创建ItemTouchHelper类的实例,参数为你自己写的那个继承callback的类,并为recylerview设置这个ItemTouchHelper.
然后就ok啦。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。