RecylerView implements long-pressing, dragging, and changing the position of the item, recylerviewitem
:
Steps:
1. Create a new class inheritance? ItemTouchHelper. Callback:
Class ItemDrag extends ItemTouchHelper. callback {// set the movable flag. I use GridLayout. All movable flags are up, down, left, right. if it is LinerLayout, It is 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 );} // This method @ Override public boolean onMove (RecyclerView recyclerView, RecyclerView. viewHolder viewHolder, RecyclerView. viewHolder target) {int fromPosition = viewHolder. getAdapterPosition (); // obtain the position int toPosition = target of the first item. getAdapterPosition (); // obtain the position Collections of the target item. swap (mChoosed, fromPosition, toPosition); // mChoosed is the data set of Recylerview. Two items are exchanged for mChoosedTagAdapter. yi TemMoved (fromPosition, toPosition); // return true for the recylerview adapter notification exchange update;} @ Override public boolean isLongPressDragEnabled () {// you can set whether to enable long-press to drag mShowIcon = true; mTagAdapter. notifyDataSetChanged (); mChoosedTagAdapter. notifyDataSetChanged (); mButton. setText ("finished"); return true ;}@ Override // callback public void onSwiped (RecyclerView. viewHolder viewHolder, int direction) {}@ Override // sets the background color pub when moving Lic void onSelectedChanged (RecyclerView. ViewHolder viewHolder, int actionState) {if (actionState! = ItemTouchHelper. ACTION_STATE_IDLE) {viewHolder. itemView. setBackgroundColor (Color. LTGRAY);} super. onSelectedChanged (viewHolder, actionState) ;}@ Override // restore the background color public void clearView (RecyclerView recyclerView, RecyclerView. viewHolder viewHolder) {super. clearView (recyclerView, viewHolder); viewHolder. itemView. setBackgroundColor (0 );}}
2. CreateItemTouchHelper class instance, Parameters are written for youThe class that inherits callbackAndRecylerview sets this ItemTouchHelper.
Then OK.