Android-自定义ViewGroup(一) 水平滑动

1.重新测量、布局

继承ViewGroup重写onMeasure和onLayout方法

1)在onMeasure中计算childVIew的测量值及模式,并设置自己的宽高

测量子View:

方法1:调用 measureChildren(widthMeasureSpec, heightMeasureSpec);
方法2:遍历childVIew调用
measureChild(childVIew, widthMeasureSpec, heightMeasureSpec);

设置自身ViewGro宽高:

设置自定义的控件MyViewGroup的大小,如果是MeasureSpec.EXACTLY则直接使用父ViewGroup传入的宽和高,否则设置为自己计算的宽和高
setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : width, heightMode == MeasureSpec.EXACTLY ? heightSize : height);

2)在onLayout中为每个子View设置布局,可以获取每个子View并分别得到子View坐标,调用child.layout(left, top,right , bottom)为子View设置布局位置。

2.滑动事件处理

3)重写onInterceptTouchEvent,在MotionEvent.ACTION_MOVE事件中通过水平、竖直方向位移大小判断,并对水平方向事件进行拦截(返回true为拦截,由自己处理)
if (Math.abs(deltaX) > Math.abs(deltaY)) {return true;}
4)重写onTouchEvent,在MotionEvent.ACTION_MOVE调用scrollBy(-deltaX, 0)实现左右滑动;在MotionEvent.ACTION_UP用scroller.startScroll(getScrollX(), 0, dx, 0, 500)限定ViewGroup左右边界

下面贴上代码,结合代码看便于理解:

public class ZhanfHorizontalScrollview extends ViewGroup {
    private int childCount;//子View数量
    private int childIndex;//子View索引
    private int measuredHeight;//子View的高度
    private int measuredWidth;//子View的宽度
    private Scroller scroller;//弹性滑动对象,用于实现View的弹性滑动
    private VelocityTracker velocityTracker;//速度追踪,

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

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

    public ZhanfHorizontalScrollview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    private void init() {
        scroller = new Scroller(getContext());
        velocityTracker = VelocityTracker.obtain();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // 获得它的父容器为它设置的测量模式和大小
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        // 1.计算自定义的ViewGroup中所有子控件的大小
        // measureChildren(widthMeasureSpec, heightMeasureSpec);
        int height = 0;
        int width = 0;

        if (childCount > 0) {
            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                if (child != null && child.getVisibility() != GONE) {
                    // 2.计算自定义的ViewGroup中所有子控件的大小
                    measureChild(child, widthMeasureSpec, heightMeasureSpec);
                    measuredHeight = child.getMeasuredHeight();
                    measuredWidth = child.getMeasuredWidth();
                    height = Math.max(height, measuredHeight);
                    width += measuredWidth;
                }
            }
        }
        // 设置自定义的控件MyViewGroup的大小,如果是MeasureSpec.EXACTLY则直接使用父ViewGroup传入的宽和高,否则设置为自己计算的宽和高
        setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : width, heightMode == MeasureSpec.EXACTLY ? heightSize : height);

    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
        childCount = getChildCount();
        int height = 0;
        int width = 0;
        if (childCount > 0) {
            for (int index = 0; index < childCount; index++) {
                View child = getChildAt(index);
                if (child.getVisibility() != GONE && child != null) {
                    measuredHeight = getMeasuredHeight();
                    measuredWidth = getMeasuredWidth();
                    height = Math.max(height, measuredHeight);
                    child.layout(width, 0, width + measuredWidth, height);
                }
                width += measuredWidth;
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        velocityTracker.addMovement(event);

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //如果动画还没有结束,再次点击时结束上次动画,即开启这次新的ACTION_DOWN的动画
                if (!scroller.isFinished()) {
                    scroller.abortAnimation();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX = x - mLastX;
                scrollBy(-deltaX, 0);
                break;
            case MotionEvent.ACTION_UP:
                int scrollX = getScrollX();//View的左边缘 - View内容的左边缘 位置的像素点
                // int scrollToChildIndex = scrollX / measuredWidth;
                velocityTracker.computeCurrentVelocity(1000);
                float xVelocity = velocityTracker.getXVelocity();//获取X方向手指滑动的速度,之前必须调用computeCurrentVelocity()方法
                if (Math.abs(xVelocity) > 200) {//当滑动速度>200Px/S时
                    childIndex = xVelocity > 0 ? childIndex - 1 : childIndex + 1;
                } else {
                    childIndex = (scrollX + measuredWidth / 2) / measuredWidth;
                }
                childIndex = Math.max(0, Math.min(childIndex, childCount - 1));//限定childIndex在0到childCount之间
                int dx = childIndex * measuredWidth - scrollX;
                scroller.startScroll(getScrollX(), 0, dx, 0, 500);//up 时自动滚动到
                invalidate();
                break;
        }
        mLastX = x;
        mLastY = y;
        return true;
    }

    @Override
    public void computeScroll() {
        if (scroller.computeScrollOffset()) {
            scrollTo(scroller.getCurrX(), scroller.getCurrY());
            postInvalidate();
        }
    }

    //分别记录上次滑动的坐标
    private int mLastX = 0;
    private int mLastY = 0;

    //分别记录上次滑动的坐标(onINterceptTouchEvent)
    private int mLastXIntercept = 0;
    private int mLastYIntercept = 0;


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        int x = (int) ev.getX();
        int y = (int) ev.getY();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!scroller.isFinished()) {
                    scroller.abortAnimation();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX = x - mLastXIntercept;
                int deltaY = y - mLastYIntercept;
                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        mLastX = x;
        mLastY = y;
        mLastXIntercept = x;
        mLastYIntercept = y;

        return super.onInterceptTouchEvent(ev);
    }
}

好了,有关水平滑动的实现就到这里。记住,自定义ViewGroup无非就是对子VIew进行逐个measure、layout,再进行相应情况的事件拦截、处理的过程,细细做下来也没那么难

参考:
《Android开发艺术探索》——3.5View的滑动冲突
Android 手把手教您自定义ViewGroup(一)

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

推荐阅读更多精彩内容