ViewDragHelper实现侧滑删除

导读

1.我特别想充分清楚的知道ViewDragHelper到底能帮我们实现哪些常见的功能?
2.使用它实现侧滑删除功能,是我见过实现侧滑删除最简单的方式

先上图


image.png

实现步骤

这是一个Listview, 每个Item都可以左滑删除~
做的过程中,肯定是在adapter的Item布局的根布局自定义一个ViewGroup,在这个自定义ViewGroup中包含两个childView,一个是正常的显示给用户的,一个是左滑出来的那个布局。如下

<com.sunny.demo.view.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipeLayout"
    android:layout_width="match_parent"
    android:layout_height="60dp" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent" >
        <TextView
            android:layout_width="70dp"
            android:background="#ccc"
            android:layout_height="match_parent"
            android:gravity="center"
            android:textColor="#fff"
            android:text="置顶" />
        <TextView
            android:id="@+id/tv_del"
            android:layout_width="70dp"
            android:background="#f00"
            android:textColor="#fff"
            android:layout_height="match_parent"
            android:gravity="center"
            android:clickable="true"
            android:text="刪除" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical" >
        <ImageView 
            android:id="@+id/imageView"
            android:src="@drawable/kxg"
            android:layout_width="50dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_height="50dp"/>
        <TextView
            android:id="@+id/textView"
            android:textColor="#444"
            android:textSize="18sp"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center_vertical"/>
    </LinearLayout>

</com.sunny.demo.view.SwipeLayout>

接下来就是要看如何自定义这个SwipeLayout了
先粘贴源码

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
/**
 * 侧滑删除
 * 
 * @author sunny
 *
 * @date  2016年1月31日
 *
 * @site www.sunnyang.com
 */
@SuppressLint("ClickableViewAccessibility")
public class SwipeLayout extends FrameLayout {

    private ViewDragHelper dragHelper;
    private OnSwipeChangeListener swipeChangeListener;
    private Status status=Status.CLOSE;//拖拽状态 默认关闭

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public static enum Status {
        OPEN, CLOSE, DRAGING
    }

    //拖拽事件监听器
    public static interface OnSwipeChangeListener {
        void onDraging(SwipeLayout mSwipeLayout);

        void onOpen(SwipeLayout mSwipeLayout);

        void onClose(SwipeLayout mSwipeLayout);
        
        void onStartOpen(SwipeLayout mSwipeLayout);
        
        void onStartClose(SwipeLayout mSwipeLayout);
        
    }

    //重写三个构造方法
    public SwipeLayout(Context context) {
        this(context, null);
    }

    public SwipeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwipeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        dragHelper = ViewDragHelper.create(this, callback);
    }

    private ViewDragHelper.Callback callback = new ViewDragHelper.Callback() {

        //所有子View都可拖拽
        public boolean tryCaptureView(View child, int pointerId) {
            return true;
        }

        //水平拖拽后处理:移动的边界进行控制
        //决定拖拽的View在水平方向上面移动到的位置

        public int clampViewPositionHorizontal(View child, int left, int dx) {
            Log.i("SwipeLayout", "left:" +left + ", dx:" + dx) ;
            if (child == frontView) {
                if (left > 0) {
                    return 0;
                } else if (left < -range) {
                    return -range; //边界不能超过-range
                }
            } else if (child == backView) {

                if (left > width) {
                    Log.i("SwipeLayout", "left"+left +" width:" + width );
                    return width;
                } else if (left < width - range) {
                    Log.i("SwipeLayout", "left"+left +" width - range:" + (width - range));
                    return width - range;
                }else {
                    Log.i("SwipeLayout", "else情况" + "left"+left +" width:" + width );
                }
            }
            return left;
        }

        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            if (changedView == frontView) {
                backView.offsetLeftAndRight(dx);
            } else if (changedView == backView) {
                frontView.offsetLeftAndRight(dx);
            }
            //事件派发
            dispatchSwipeEvent();
            //兼容低版本
            invalidate();
        };
        
        //松手后根据侧滑位移确定菜单打开与否
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            if (xvel == 0 && frontView.getLeft() < -range * 0.5f) {
                open();
            } else if (xvel < 0) {
                open();
            } else {
                close();
            }
        };
        
        //子View如果是clickable,必须重写的方法
        public int getViewHorizontalDragRange(View child) {
            return 1;
        }

        public int getViewVerticalDragRange(View child) {
            return 1;
        }
    };

    //根据当前状态判断回调事件
    protected void dispatchSwipeEvent() {
        Status preStatus=status;
        status=updateStatus();
        
        if(swipeChangeListener!=null){
            swipeChangeListener.onDraging(this);
        }
        
        if(preStatus!=status&&swipeChangeListener!=null){
            if(status==Status.CLOSE){
                swipeChangeListener.onClose(this);
            }else if(status==Status.OPEN){
                swipeChangeListener.onOpen(this);
            }else if(status==Status.DRAGING){
                if(preStatus==Status.CLOSE){
                    swipeChangeListener.onStartOpen(this);
                }else if(preStatus==Status.OPEN){
                    swipeChangeListener.onStartClose(this);
                }
            }
        }
    }

    //更改状态
    private Status updateStatus() {
        int left=frontView.getLeft();
        if(left==0){
            return Status.CLOSE;
        }else if(left==-range){
            return Status.OPEN;
        }
        return Status.DRAGING;
    }

    private View backView;//侧滑菜单
    private View frontView;//内容区域
    private int height;//自定义控件布局高
    private int width;//自定义控件布局宽
    private int range;//侧滑菜单可滑动范围

    // 持续平滑动画 高频调用
    public void computeScroll() {
        // 如果返回true,动画还需要继续
        if (dragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this);
        }
    };

    public void open() {
        open(true);
    }

    public void open(boolean isSmooth) {
        int finalLeft = -range;
        if (isSmooth) {
            if (dragHelper.smoothSlideViewTo(frontView, finalLeft, 0)) {
                ViewCompat.postInvalidateOnAnimation(this);
            }
        } else {
            layoutContent(true);
        }
    }

    public void close() {
        close(true);
    }

    public void close(boolean isSmooth) {
        int finalLeft = 0;
        if (isSmooth) {
            if (dragHelper.smoothSlideViewTo(frontView, finalLeft, 0)) {
                ViewCompat.postInvalidateOnAnimation(this);
            }
        } else {
            layoutContent(false);
        }
    }

    //布局子View
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        layoutContent(false);

    }

    /**
     * @param isOpen 侧滑菜单是否打开
     */
    private void layoutContent(boolean isOpen) {
        Rect frontRect = computeFrontViewRect(isOpen);
        frontView.layout(frontRect.left, frontRect.top, frontRect.right, frontRect.bottom);

        Rect backRect = computeBackViewRect(frontRect);
        backView.layout(backRect.left, backRect.top, backRect.right, backRect.bottom);

        //调整顺序
//      bringChildToFront(frontView);
    }

    /**
     * 通过内容区域所占矩形坐标计算侧滑菜单的矩形位置区域
     * @param frontRect 内容区域所占矩形
     * @return
     */
    private Rect computeBackViewRect(Rect frontRect) {
        int left = frontRect.right;
        return new Rect(left, 0, left + range, height);
    }

    /**
     * 通过菜单打开与否isOpen计算内容区域的矩形区
     * @param isOpen
     * @return
     */
    private Rect computeFrontViewRect(boolean isOpen) {
        int left = 0;
        if (isOpen) {
            left = -range;
        }
        return new Rect(left, 0, left + width, height);
    }

    //获取两个View
    protected void onFinishInflate() {
        super.onFinishInflate();

        int childCount = getChildCount();
        if (childCount < 2) {
            throw new IllegalStateException("you need 2 children view");
        }
        if (!(getChildAt(0) instanceof ViewGroup) || !(getChildAt(1) instanceof ViewGroup)) {
            throw new IllegalArgumentException("your children must be instance of ViewGroup");
        }

        backView = getChildAt(0);//侧滑菜单
        frontView = getChildAt(1);//内容区域

    }

    //初始化布局的高height宽width以及可滑动的范围range
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        height = frontView.getMeasuredHeight();
        width = frontView.getMeasuredWidth();
        range = backView.getMeasuredWidth();
        Log.i("SwipeLayout","height :" + height + "  width :" + height + "  range :" + height);

    }

    public boolean onInterceptTouchEvent(android.view.MotionEvent ev) {
        return dragHelper.shouldInterceptTouchEvent(ev);
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        dragHelper.processTouchEvent(event);
        return true;
    }

    public void setSwipeChangeListener(OnSwipeChangeListener swipeChangeListener) {
        this.swipeChangeListener = swipeChangeListener;
    }

}

解读SwipeLayout

1.第一步当然是获取FrameLayout下的子View对象,有了子view对象,就可以很方便的获取子View的宽高。
获取子View对象的方法是onFinishInflate。

//获取两个View
    protected void onFinishInflate() {
        super.onFinishInflate();

        int childCount = getChildCount();
        if (childCount < 2) {
            throw new IllegalStateException("you need 2 children view");
        }
        if (!(getChildAt(0) instanceof ViewGroup) || !(getChildAt(1) instanceof ViewGroup)) {
            throw new IllegalArgumentException("your children must be instance of ViewGroup");
        }

        backView = getChildAt(0);//侧滑菜单
        frontView = getChildAt(1);//内容区域

    }

2.获取子View的宽高

//初始化布局的高height宽width以及可滑动的范围range
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        height = frontView.getMeasuredHeight();
        width = frontView.getMeasuredWidth();
        range = backView.getMeasuredWidth();
        Log.i("SwipeLayout","height :" + height + "  width :" + height + "  range :" + height);

    }

3.这里选择的是继承FrameLayout,那就要注意把backView(侧滑菜单)先放在屏幕最右侧的右边,即在用户刚好看不见的地方。frontView(内容区域)的宽度铺满屏幕,高度为frontView的测量高度。想到在哪个方法执行这个方法了吗?bingo,当然是onLayout了。
childView.layout(......) 方法就可以把childView放在指定的位置上

4.所以的子View都可以被拖拽,所以tryCaptureView 返回true就好

5.public int clampViewPositionHorizontal(View child, int left, int dx) , 这个方法的内容比较难理解。我们要控制frontView的做边界
-range ~0, backView的边界是width-range ~ width

6.public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) :调用了offsetLeftAndRight移动backView和frontView,同时添加了一些监听。

7.public void onViewReleased(View releasedChild, float xvel, float yvel):松手后根据侧滑位移确定菜单打开与否。

8.代码当中涉及到的功能点有:

  • 8.1当松手以后,view平滑的打开或者关闭的处理
  • 8.2如何实时触发不同状态的监听,比如拖拽状态,打开结束状态,关闭结束状态,正要打开的状态,正要结束的状态。
  • 8.3view如何依据手指的移动而移动~

源码地址

源码参考我的github地址

总结

自定义View不容易,且行且珍惜啊~

参考

http://www.cnblogs.com/aademeng/articles/6542188.html
http://www.sunnyang.com/358.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容