Android ItemTouchHelper enables sliding deletion and movement

ItemTouchHelper

The detailed content can be searched by yourself. Here is a brief personal understanding

It is a tool class that can drag and drop listview internal components to realize location exchange, deletion and other functions

The simple implementation of this class can be divided into four steps (pure personal understanding)

  1. Create a subclass of ItemTouchHelper.Callback
  2. Write the interface of the two methods to be implemented (moving exchange position and sliding deletion) (you can skip to step 3 without writing)
  3. Implement the interface with your own Adapter (override two methods)
  4. Called within the onCreateView method of a class

Preparation of ItemTouchHelper subclass

public class ItemTouchCallback extends ItemTouchHelper.Callback {

        private CrimeAdapter mCrimeAdapter;

        public ItemTouchCallback(CrimeAdapter crimeAdapter) {
            this.mCrimeAdapter = crimeAdapter;
        }

        @Override
        public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
            //Allow drag up and down
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            //Only right to left sideslip is allowed
            int swipeFlags = ItemTouchHelper.LEFT;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {

            mCrimeAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
            return true;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {

            mCrimeAdapter.onItemDismiss(viewHolder.getAdapterPosition());//Call our custom method
        }

        @Override
        public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
                //Change the transparency of Item when sliding
                final float alpha = 1 - Math.abs(dX) / (float)viewHolder.itemView.getWidth();
                viewHolder.itemView.setAlpha(alpha);
            }
        }
    }

Here we mainly implement some methods of ItemTouchHelper. If you don't have high requirements for personalized customization, you don't have to modify it

Write interface

    public interface IOperationData {
        /**
         * Data exchange
         * @param fromPosition
         * @param toPosition
         */
        void onItemMove(int fromPosition,int toPosition);

        /**
         * Data deletion
         * @param position
         */
        void onItemDismiss(int position);
    }

Just tell yourself what methods need to be implemented to make the code structure clearer and more readable

Adapter implementation interface

    private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> implements IOperationData {

        private List<Crime> mCrimes;

        public CrimeAdapter(List<Crime> crimes) {
            mCrimes = crimes;

        }

        @Override
        public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());

            return new CrimeHolder(layoutInflater, parent);
        }

        @Override
        public void onBindViewHolder(CrimeHolder holder, int position) {
            Crime crime = mCrimes.get(position);
            holder.bind(crime);
        }

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

        public void setCrimes(List<Crime> crimes) {
            mCrimes = crimes;
        }

                @Override
        public void onItemMove(int fromPosition, int toPosition) {
            //change of position
            Collections.swap(mCrimes,fromPosition,toPosition);
            notifyItemMoved(fromPosition,toPosition);
        }

        @Override
        public void onItemDismiss(int position) {
            //Remove data
            CrimeLab.get(getActivity()).deleterCrime(mCrimes.get(position));
            mCrimes.remove(position);
            notifyItemRemoved(position);
        }
    }

The first sentence of onitemdisassiss() can be omitted if the database operation is not required when removing data;
If you change the location, you can only modify the location temporarily. For students who need to modify the location persistently, you may need to think about the database yourself (because it's just an assignment, so I touched it!)

call

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_crime_list, container, false);

        mCrimeRecyclerView = (RecyclerView) view
                .findViewById(R.id.crime_recycler_view);
        mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        if (savedInstanceState != null) {
            mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE);
        }


        updateUI();

        //Calling ItemTouchHelper
        ItemTouchCallback callback = new ItemTouchCallback(mAdapter);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(mCrimeRecyclerView);

        return view;
    }

With my many attempts, putting the calling code in this position can perfectly fit my project structure! (other places will flash back)
I'm not very clear about the specific reason... If the project structure is different, students can refer to the following code (gitee) or try it several times by themselves, and they should be able to find a suitable location
(if you know the reason, you can leave a message to didi me!)

Reference articles and codes:
  • https://blog.csdn.net/u014133119/article/details/80942932
  • https://gitee.com/Android5x/itemtouchhelperdemo?_from=gitee_search
Full text code (to students in need)
  • https://gitee.com/luckku/CriminalIntent-ItemTouchHelper

I hope this article is helpful to you. Here is Le Yu!
(do you have any students from information technology to copy your homework...? leave me a message quickly)

Keywords: Android

Added by gapern on Tue, 19 Oct 2021 06:50:57 +0300