讓你的ListView更炫酷,實現側滑刪除效果

博文出處:讓你的ListView更炫酷,實現側滑刪除效果,歡迎大家關注我的博客,謝謝!

又到了更新博客的時間了,今天給大家帶來的是ListView側滑出現刪除等按鈕的效果。相信大家在平時玩app的時候都接觸過這種效果吧。比如說QQ聊天列表側滑就會出現“置頂”、“標為已讀”、“刪除”等按鈕。這篇博文將用ViewDragHelper這個神器來實現側滑效果。友情鏈接一下之前寫的博文使用ViewDragHelper來實現側滑菜單的,點擊此處跳轉。如果你對ViewDragHelper不熟悉,你可以去看看鴻洋_《Android ViewDragHelper完全解析 自定義ViewGroup神器》

好了,話說的那么多,先來看看我們實現的效果圖吧:

側滑ListView效果圖.gif

可以看出來,我們實現的和QQ的效果相差無幾。下面就是源碼時間了。

先來看一下ListView的item的slip_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<com.yuqirong.swipelistview.view.SwipeListLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/sll_main"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tv_top"
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:background="#66ff0000"
            android:gravity="center"
            android:text="置頂" />

        <TextView
            android:id="@+id/tv_delete"
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:background="#330000ff"
            android:gravity="center"
            android:text="刪除" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:background="#66ffffff"
        android:orientation="horizontal" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:src="@drawable/head_1" />

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:gravity="center_vertical"
            android:text="hello" />
    </LinearLayout>

</com.yuqirong.swipelistview.view.SwipeListLayout>

我們可以看出,要先把側滑出的按鈕布局放在SwipeListLayout的第一層,而item的布局放在第二層。還有一點要注意的是,側滑出的按鈕如果有兩個或兩個以上,那么必須用ViewGroup作為父布局。要整體保持SwipeListLayout的直接子View為2個。

而activity的布局文件里就是一個ListView,這里就不再給出了。

下面我們直接來看看SwipeListLayout的內容:

public SwipeListLayout(Context context) {
    this(context, null);
}

public SwipeListLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    mDragHelper = ViewDragHelper.create(this, callback);
}

// ViewDragHelper的回調
Callback callback = new Callback() {

    @Override
    public boolean tryCaptureView(View view, int arg1) {
        return view == itemView;
    }

    @Override
    public int clampViewPositionHorizontal(View child, int left, int dx) {
        if (child == itemView) {
            if (left > 0) {
                return 0;
            } else {
                left = Math.max(left, -hiddenViewWidth);
                return left;
            }
        }
        return 0;
    }

    @Override
    public int getViewHorizontalDragRange(View child) {
        return hiddenViewWidth;
    }

    @Override
    public void onViewPositionChanged(View changedView, int left, int top,
            int dx, int dy) {
        if (itemView == changedView) {
            hiddenView.offsetLeftAndRight(dx);
        }
        // 有時候滑動很快的話 會出現隱藏按鈕的linearlayout沒有繪制的問題
        // 為了確保繪制成功 調用 invalidate
        invalidate();
    }

    public void onViewReleased(View releasedChild, float xvel, float yvel) {
        // 向右滑xvel為正 向左滑xvel為負
        if (releasedChild == itemView) {
            if (xvel == 0
                    && Math.abs(itemView.getLeft()) > hiddenViewWidth / 2.0f) {
                open(smooth);
            } else if (xvel < 0) {
                open(smooth);
            } else {
                close(smooth);
            }
        }
    }

};

我們主要來看callback,首先在tryCaptureView(View view, int arg1)里設置了只有是itemView的時候才能被捕獲,也就是說當你去滑動“刪除”、“置頂”等按鈕的時候,側滑按鈕是不會被關閉的,因為根本就沒捕獲。(當然你也可以設置都捕獲,那樣的話下面的邏輯要調整了),剩余的幾個函數中的邏輯較為簡單,在onView Released(View releasedChild, float xvel, float yvel)也是判斷了當手指抬起時itemView所處的位置。如果向左滑或者停止滑動時按鈕已經顯示出1/2的寬度,則打開;其余情況下都將關閉按鈕。

以下分別是close()和open()的方法:

/**
 * 側滑關閉
 * 
 * @param smooth
 *            為true則有平滑的過渡動畫
 */
private void close(boolean smooth) {
    preStatus = status;
    status = Status.Close;
    if (smooth) {
        if (mDragHelper.smoothSlideViewTo(itemView, 0, 0)) {
            if (listener != null) {
                Log.i(TAG, "start close animation");
                listener.onStartCloseAnimation();
            }
            ViewCompat.postInvalidateOnAnimation(this);
        }
    } else {
        layout(status);
    }
    if (listener != null && preStatus == Status.Open) {
        Log.i(TAG, "close");
        listener.onStatusChanged(status);
    }
}

/**
 * 側滑打開
 * 
 * @param smooth
 *            為true則有平滑的過渡動畫
 */
private void open(boolean smooth) {
    preStatus = status;
    status = Status.Open;
    if (smooth) {
        if (mDragHelper.smoothSlideViewTo(itemView, -hiddenViewWidth, 0)) {
            if (listener != null) {
                Log.i(TAG, "start open animation");
                listener.onStartOpenAnimation();
            }
            ViewCompat.postInvalidateOnAnimation(this);
        }
    } else {
        layout(status);
    }
    if (listener != null && preStatus == Status.Close) {
        Log.i(TAG, "open");
        listener.onStatusChanged(status);
    }
}

SwipeListLayout大致的代碼就這些,相信對于熟悉ViewDragHelper的同學們來說應該是不成問題的。其實整體的邏輯和之前用ViewDragHelper來實現側滑菜單大同小異。

順便下面貼出SwipeListLayout的全部代碼:

/**
 * 側滑Layout
 */
public class SwipeListLayout extends FrameLayout {

    private View hiddenView;
    private View itemView;
    private int hiddenViewWidth;
    private ViewDragHelper mDragHelper;
    private int hiddenViewHeight;
    private int itemWidth;
    private int itemHeight;
    private OnSwipeStatusListener listener;
    private Status status = Status.Close;
    private boolean smooth = true;

    public static final String TAG = "SlipListLayout";

    // 狀態
    public enum Status {
        Open, Close
    }

    /**
     * 設置側滑狀態
     * 
     * @param status
     *            狀態 Open or Close
     * @param smooth
     *            若為true則有過渡動畫,否則沒有
     */
    public void setStatus(Status status, boolean smooth) {
        this.status = status;
        if (status == Status.Open) {
            open(smooth);
        } else {
            close(smooth);
        }
    }

    public void setOnSwipeStatusListener(OnSwipeStatusListener listener) {
        this.listener = listener;
    }

    /**
     * 是否設置過渡動畫
     * 
     * @param smooth
     */
    public void setSmooth(boolean smooth) {
        this.smooth = smooth;
    }

    public interface OnSwipeStatusListener {

        /**
         * 當狀態改變時回調
         * 
         * @param status
         */
        void onStatusChanged(Status status);

        /**
         * 開始執行Open動畫
         */
        void onStartCloseAnimation();

        /**
         * 開始執行Close動畫
         */
        void onStartOpenAnimation();

    }

    public SwipeListLayout(Context context) {
        this(context, null);
    }

    public SwipeListLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mDragHelper = ViewDragHelper.create(this, callback);
    }

    // ViewDragHelper的回調
    Callback callback = new Callback() {

        @Override
        public boolean tryCaptureView(View view, int arg1) {
            return view == itemView;
        }

        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            if (child == itemView) {
                if (left > 0) {
                    return 0;
                } else {
                    left = Math.max(left, -hiddenViewWidth);
                    return left;
                }
            }
            return 0;
        }

        @Override
        public int getViewHorizontalDragRange(View child) {
            return hiddenViewWidth;
        }

        @Override
        public void onViewPositionChanged(View changedView, int left, int top,
                int dx, int dy) {
            if (itemView == changedView) {
                hiddenView.offsetLeftAndRight(dx);
            }
            // 有時候滑動很快的話 會出現隱藏按鈕的linearlayout沒有繪制的問題
            // 為了確保繪制成功 調用 invalidate
            invalidate();
        }

        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            // 向右滑xvel為正 向左滑xvel為負
            if (releasedChild == itemView) {
                if (xvel == 0
                        && Math.abs(itemView.getLeft()) > hiddenViewWidth / 2.0f) {
                    open(smooth);
                } else if (xvel < 0) {
                    open(smooth);
                } else {
                    close(smooth);
                }
            }
        }

    };
    private Status preStatus = Status.Close;

    /**
     * 側滑關閉
     * 
     * @param smooth
     *            為true則有平滑的過渡動畫
     */
    private void close(boolean smooth) {
        preStatus = status;
        status = Status.Close;
        if (smooth) {
            if (mDragHelper.smoothSlideViewTo(itemView, 0, 0)) {
                if (listener != null) {
                    Log.i(TAG, "start close animation");
                    listener.onStartCloseAnimation();
                }
                ViewCompat.postInvalidateOnAnimation(this);
            }
        } else {
            layout(status);
        }
        if (listener != null && preStatus == Status.Open) {
            Log.i(TAG, "close");
            listener.onStatusChanged(status);
        }
    }

    /**
     * 
     * @param status
     */
    private void layout(Status status) {
        if (status == Status.Close) {
            hiddenView.layout(itemWidth, 0, itemWidth + hiddenViewWidth,
                    itemHeight);
            itemView.layout(0, 0, itemWidth, itemHeight);
        } else {
            hiddenView.layout(itemWidth - hiddenViewWidth, 0, itemWidth,
                    itemHeight);
            itemView.layout(-hiddenViewWidth, 0, itemWidth - hiddenViewWidth,
                    itemHeight);
        }
    }

    /**
     * 側滑打開
     * 
     * @param smooth
     *            為true則有平滑的過渡動畫
     */
    private void open(boolean smooth) {
        preStatus = status;
        status = Status.Open;
        if (smooth) {
            if (mDragHelper.smoothSlideViewTo(itemView, -hiddenViewWidth, 0)) {
                if (listener != null) {
                    Log.i(TAG, "start open animation");
                    listener.onStartOpenAnimation();
                }
                ViewCompat.postInvalidateOnAnimation(this);
            }
        } else {
            layout(status);
        }
        if (listener != null && preStatus == Status.Close) {
            Log.i(TAG, "open");
            listener.onStatusChanged(status);
        }
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        // 開始執行動畫
        if (mDragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this);
        }
    }

    // 讓ViewDragHelper來處理觸摸事件
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();
        if (action == MotionEvent.ACTION_CANCEL) {
            mDragHelper.cancel();
            return false;
        }
        return mDragHelper.shouldInterceptTouchEvent(ev);
    }

    // 讓ViewDragHelper來處理觸摸事件
    public boolean onTouchEvent(MotionEvent event) {
        mDragHelper.processTouchEvent(event);
        return true;
    };

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        hiddenView = getChildAt(0); // 得到隱藏按鈕的linearlayout
        itemView = getChildAt(1); // 得到最上層的linearlayout
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 測量子View的長和寬
        itemWidth = itemView.getMeasuredWidth();
        itemHeight = itemView.getMeasuredHeight();
        hiddenViewWidth = hiddenView.getMeasuredWidth();
        hiddenViewHeight = hiddenView.getMeasuredHeight();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
            int bottom) {
        layout(Status.Close);
    }

}

最后,提供SwipeListLayout的源碼下載:

SwipeListView.rar

GitHub:

SwipeListView

~have fun!~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容