1. 程式人生 > >RecycleView實現側滑刪除item

RecycleView實現側滑刪除item

以及 urn 接口 add 是個 pre ack 編寫 ner

對於列表空間的側滑操作,網上有很多開源的空間可以使用,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
     * [email protected]
/* */ #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
         * [email protected]
/* */ #getSwipeDirs(RecyclerView, ViewHolder)} * and / or [email protected] #getDragDirs(RecyclerView, ViewHolder)}. * * @param dragDirs Binary OR of direction flags in which the Views can be dragged. Must be * composed of [email protected] #LEFT}, [email protected] #RIGHT}, [email protected] #START}, [email protected] * #END}, * [email protected] #UP} and [email protected] #DOWN}. * @param swipeDirs Binary OR of direction flags in which the Views can be swiped. Must be * composed of [email protected] #LEFT}, [email protected] #RIGHT}, [email protected] #START}, [email protected] * #END}, * [email protected] #UP} and [email protected] #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在滑動的時候調用。實現的邏輯需要自己編寫,實現起來也不困難。

RecycleView實現側滑刪除item