current position:Home>Android uses itemtouchhelper to realize item dragging position exchange and side sliding deletion of recyclerview

Android uses itemtouchhelper to realize item dragging position exchange and side sliding deletion of recyclerview

2022-06-24 09:35:31Mars-xq

demo:

package com.xq.myapplication;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/** * @author xuqiang18 * @since 2022/6/10 9:56 */
public class MainActivity5 extends AppCompatActivity {
    

    private final List<String> mData = new ArrayList<>();
    private RvAdapter rvAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main5);

        this.findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
    
                rvAdapter.notifyDataSetChanged();
            }
        });
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        for (int i = 0; i < 200; i++) {
    
            mData.add("source" + i);
        }
        rvAdapter = new RvAdapter(mData);
        recyclerView.setAdapter(rvAdapter);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 8));

        MyItemTouchHelper myItemTouchHelper = new MyItemTouchHelper(mData);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(myItemTouchHelper);
        itemTouchHelper.attachToRecyclerView(recyclerView);
    }


    /** *  Handle RecycleView Selection of , Drag to move , Drag and drop the deleted implementation class  */
    public static class MyItemTouchHelper extends ItemTouchHelper.Callback {
    
        private static final String TAG = MyItemTouchHelper.class.getSimpleName();

        private final List<String> mData;
        private RecyclerView mRecyclerView;

        public MyItemTouchHelper(List<String> mData) {
    
            this.mData = mData;
        }

        @Override
        public int getMovementFlags(RecyclerView recyclerView,
                                    @NonNull RecyclerView.ViewHolder viewHolder) {
    
            Log.e(TAG, "getMovementFlags: ===================================");
            this.mRecyclerView = recyclerView;
            int dragFlags;
            if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
    
                dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                        ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            } else {
    
                dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            }
            // Sideslip delete direction 
            int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean isLongPressDragEnabled() {
    
            return true;  // Whether to enable long press drag 
        }

        @Override
        public boolean isItemViewSwipeEnabled() {
    
            return true; // Whether to enable sideslip drag delete 
        }

        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView,
                              @NonNull RecyclerView.ViewHolder source,
                              @NonNull RecyclerView.ViewHolder target) {
    
            Log.e(TAG, "onMove: ===================================");
            // Transfer the starting position and target position of the drag and drop exchange data through the interface ViewHolder
            RvAdapter adapter = (RvAdapter) recyclerView.getAdapter();
            if (adapter != null) {
    
                int fromPosition = source.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
                if (fromPosition < mData.size() && toPosition < mData.size()) {
    
                    // Exchange data location 
                    Collections.swap(mData, fromPosition, toPosition);
                    // Refresh location swap 
                    adapter.notifyItemMoved(fromPosition, toPosition);
                }
            }
            return true;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
    
            Log.e(TAG, "onSwiped: ===================================");
            // Move delete callback , If not, you can ignore it 
            if (mRecyclerView != null) {
    
                RvAdapter adapter = (RvAdapter) mRecyclerView.getAdapter();
                if (adapter != null) {
    
                    int position = viewHolder.getAdapterPosition();
                    mData.remove(position); // Remove data 
                    adapter.notifyItemRemoved(position);// Refresh data remove 
                }
            }
        }

        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
    
            super.onSelectedChanged(viewHolder, actionState);
            Log.e(TAG, "onSelectedChanged: ===================================");
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
    
                // When sliding or dragging view Return this through the interface ViewHolder
                // Zoom in on the selected when dragging view
                viewHolder.itemView.setScaleX(1.2f);
                viewHolder.itemView.setScaleY(1.2f);
                viewHolder.itemView.setBackgroundColor(Color.RED);
            }
        }

        @Override
        public void clearView(@NonNull RecyclerView recyclerView,
                              @NonNull RecyclerView.ViewHolder viewHolder) {
    
            super.clearView(recyclerView, viewHolder);
            Log.e(TAG, "clearView: ===================================");
            if (!recyclerView.isComputingLayout()) {
    
                // When it is necessary to clear before onSelectedChanged perhaps 
                // onChildDraw,onChildDrawOver When setting the status or animating, the interface returns the ViewHolder
                viewHolder.itemView.setScaleX(1.0f);
                viewHolder.itemView.setScaleY(1.0f);
                viewHolder.itemView.setBackgroundColor(Color.BLUE);
            }
        }
    }

    public static class RvAdapter extends RecyclerView.Adapter<RvAdapter.VHolder> {
    

        private final List<String> mData;

        public RvAdapter(List<String> mData) {
    
            this.mData = mData;
        }

        @NonNull
        @Override
        public VHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_rv, parent, false);
            return new VHolder(view);
        }

        @Override
        public void onBindViewHolder(RvAdapter.VHolder holder, int position) {
    
            holder.mTextView1.setText(mData.get(position));
            holder.mTextView2.setText(String.valueOf(position));
        }

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

        public static class VHolder extends RecyclerView.ViewHolder {
    

            private final TextView mTextView1;
            private final TextView mTextView2;

            public VHolder(View itemView) {
    
                super(itemView);

                mTextView1 = (TextView) itemView.findViewById(R.id.tv1);
                mTextView2 = (TextView) itemView.findViewById(R.id.tv2);
            }
        }
    }

}

activity_main5.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">

    <Button android:layout_width="wrap_content" android:id="@+id/btn" android:text=" Refresh " android:layout_height="wrap_content"/>

    <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" tools:itemCount="50" tools:listitem="@layout/item_rv" />

</LinearLayout>

item_rv.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="80dp" android:layout_margin="10dp" android:background="@android:color/holo_blue_dark" android:gravity="center" android:orientation="vertical">

    <TextView android:id="@+id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textColor="@android:color/white" android:textSize="18sp" tools:text="@tools:sample/cities" />

    <TextView android:id="@+id/tv2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textColor="@android:color/white" android:textSize="14sp" tools:text="@tools:sample/cities" />

</LinearLayout>

copyright notice
author[Mars-xq],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/175/202206240810453003.html

Random recommended