RecycleView實現側滑刪除item


  對於列表空間的側滑操作,網上有很多開源的空間可以使用,Google在它的新控件RecycleView中增加了側滑的API,完全遵循Material Design設計規范,下面看看效果演示:

  

 

下面看看介紹一下刷新控制類:  ItemTouchHelper。

  顧名思義,這個類就是來幫助我們對於item執行更多的操作。下面看看具體操作:

  我們實例化這個類的時候需要傳入對應的會掉接口:

 

/**
     * Creates an ItemTouchHelper that will work with the given Callback.
     * <p>
     * You can attach ItemTouchHelper to a RecyclerView via
     * {@link #attachToRecyclerView(RecyclerView)}. Upon attaching, it will add an item decoration,
     * an onItemTouchListener and a Child attach / detach listener to the RecyclerView.
     *
     * @param callback The Callback which controls the behavior of this touch helper.
     */
    public ItemTouchHelper(Callback callback) {
        mCallback = callback;
    }

看源碼會發現這個接口是個抽象類,我們看看ItemTouchHelper中寫了一個抽象類繼承與該抽象類:

  

  /**
         * Creates a Callback for the given drag and swipe allowance. These values serve as
         * defaults
         * and if you want to customize behavior per ViewHolder, you can override
         * {@link #getSwipeDirs(RecyclerView, ViewHolder)}
         * and / or {@link #getDragDirs(RecyclerView, ViewHolder)}.
         *
         * @param dragDirs  Binary OR of direction flags in which the Views can be dragged. Must be
         *                  composed of {@link #LEFT}, {@link #RIGHT}, {@link #START}, {@link
         *                  #END},
         *                  {@link #UP} and {@link #DOWN}.
         * @param swipeDirs Binary OR of direction flags in which the Views can be swiped. Must be
         *                  composed of {@link #LEFT}, {@link #RIGHT}, {@link #START}, {@link
         *                  #END},
         *                  {@link #UP} and {@link #DOWN}.
         */
        public SimpleCallback(int dragDirs, int swipeDirs) {
            mDefaultSwipeDirs = swipeDirs;
            mDefaultDragDirs = dragDirs;
        }

 在實現了它的適合需要傳入兩個參數,一個是拖出來的方向以及滑動的方向,通常我們只需要指定后者的參數,前置置為0即可。以下是可選參數。

 /**
     * Up direction, used for swipe & drag control.
     */
    public static final int UP = 1;

    /**
     * Down direction, used for swipe & drag control.
     */
    public static final int DOWN = 1 << 1;

    /**
     * Left direction, used for swipe & drag control.
     */
    public static final int LEFT = 1 << 2;

    /**
     * Right direction, used for swipe & drag control.
     */
    public static final int RIGHT = 1 << 3;

當我們實現了這個抽象類之后需要復寫它的三個方法,當然也可以繼承於它。接下來是具體實現代碼。

 ItemTouchHelper touchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                //滑動時的一些操作
                isDelete = false;
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                // 處理滑動事件回調
                final int pos = viewHolder.getAdapterPosition();
                ImActiveChat imActiveChat = imActiveChatList.get(pos);
                imActiveChatList.remove(pos);
                chatRVAdapter.notifyItemRemoved(pos);
                if (imActiveChatList.size()==0){
                    rvSingleChat.setVisibility(View.GONE);
                    tvNoMessage.setVisibility(View.VISIBLE);

                }
                String text;
                isDelete = true;
                // 判斷方向,進行不同的操作
                if (direction == ItemTouchHelper.RIGHT) {

                    text = "刪除了和" + imActiveChat.getUserId() + "的聊天";

                } else {

                    text = "刪除了和" + imActiveChat.getUserId() + "的聊天";
                }

                Snackbar.make(viewHolder.itemView, text, Snackbar.LENGTH_SHORT)

                        .setAction("取消", v -> {

                            imActiveChatList.add(pos, imActiveChat);
                            chatRVAdapter.notifyItemInserted(pos);
                            isDelete = false;

                        }).setCallback(new Snackbar.Callback() {
                    @Override
                    public void onDismissed(Snackbar snackbar, int event) {
                        super.onDismissed(snackbar, event);
                        if (isDelete) {
                            StorageImActiveChat.getInstance((Application) UiUtils.getContext()).deleteAChatRoom(imActiveChat);
                            //未讀消息刪除
                            Flowable.fromCallable(() -> StorageImMessage.getInstance(QNApplication.getContext()).findMessageById(imActiveChat.getUserId(), 100)).subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(SingleChatListFragment.this::setMessageReaded);

                        }
                    }
                }).show();


            }

            //處理動畫
            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
                    //滑動時改變 Item 的透明度,以實現滑動過程中實現漸變效果
                    final float alpha = 1 - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
                    viewHolder.itemView.setAlpha(alpha);
                    viewHolder.itemView.setTranslationX(dX);
                } else {
                    super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
                }
            }
            //滑動事件完成時回調
            //在這里可以實現撤銷操作

            //是否長按進行拖拽
            @Override
            public boolean isLongPressDragEnabled() {
                return true;
            }
        });
        touchHelper.attachToRecyclerView(recycleview);

onMove在滑動結束的時候調用,而onSwip在滑動的時候調用。實現的邏輯需要自己編寫,實現起來也不困難。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM