自定义可以滚动的线性布局

自定义滚动的线性布局主要需要完成下面3个功能

1 计算子view及本身的尺寸
2 把子view布局到指定的位置
3 添加滑动事件

1 计算尺寸

需要重写下面这个方法

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

参数中的widthMeasureSpecheightMeasureSpec是包含宽和高的信息。里面放了测量模式和尺寸大小,具体获取方法

int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);

MeasureSpec.AT_MOST对应布局中的WRAP_CONTENT,MeasureSpec.EXACTLY对应MATCH_PARENT和固定的尺寸,MeasureSpec.UNSPECIFIED指未指定尺寸,这种情况很少
如果宽高是自适应的、就需要我们自己来计算实际尺寸大小
要实现可以滚动的水平线性布局viewGroup的最大宽度实际上就是所有子view中最宽的view的宽度,最大高度是所有子view高度的和

 private int getMaxChildWidth() {
   int childCount = getChildCount();
   int maxWidth = 0;
   for (int i = 0; i < childCount; i++) {
     View childView = getChildAt(i);
     if (childView.getMeasuredWidth() > maxWidth)
     maxWidth = childView.getMeasuredWidth();
    }
      return maxWidth
  }
 private int getTotleHeight() {
  int childCount = getChildCount();
  int height = 0;
  for (int i = 0; i < childCount; i++) {
    View childView = getChildAt(i);
    height += childView.getMeasuredHeight();
   }
     return height;
  }

重写onMeasure方法

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        //如果宽高都是包裹内容
        if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
            //我们将高度设置为所有子View的高度相加,宽度设为子View中最大的宽度
            int height = getTotleHeight();
            int width = getMaxChildWidth();
            setMeasuredDimension(width, height);

        } else if (heightMode == MeasureSpec.AT_MOST) {//如果只有高度是包裹内容
            //宽度设置为ViewGroup自己的测量宽度,高度设置为所有子View的高度总和
            setMeasuredDimension(widthSize, getTotleHeight());
        } else if (widthMode == MeasureSpec.AT_MOST) {//如果只有宽度是包裹内容
            //宽度设置为子View中宽度最大的值,高度设置为ViewGroup自己的测量值
            setMeasuredDimension(getMaxChildWidth(), heightSize);

        } else {
            setMeasuredDimension(widthSize, heightSize);
        }
    }

尺寸计算好了,下面就要布局子view了

2 布局子view

实现起来很简单

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        int top = 0;
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            int measuredHeight = child.getMeasuredHeight();
            int measuredWidth = child.getMeasuredWidth();
            child.layout(0, top, measuredWidth, top + measuredHeight);
            top += measuredHeight;
        }
    }
3 添加滑动事件

添加滑动事件就要重写onTouchEvent方法了,可以用手势帮助类GestureDetector来实现

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mGesture.onTouchEvent(event);
        return true;
    }
    private void init() {
     mGesture = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                scrollBy(0, (int) distanceY);
                return true;
            }
        });
    }

到此,可以滑动的线性布局就基本完成了,但是还存在一些缺陷,滑动会超过边界、没有惯性滑动
首先先来解决滑动超过边界的问题,思路是在手指抬起的时候如果滑动超过边界,就重新滚动到边界,为了使滑动流畅,使用OverScroller实现,修改之前的onTouchEvent

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mGesture.onTouchEvent(event);
        if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
            if (getScrollY() < 0) {
                mScroller.startScroll(0, getScrollY(), 0, -getScrollY());
                invalidate();
            }
            View lastChild = getChildAt(getChildCount() - 1);
            int bottomY = (int) (lastChild.getY() + lastChild.getMeasuredHeight() - screenHeight);
            if (getScrollY() > bottomY) {
                mScroller.startScroll(0, getScrollY(), 0, bottomY - getScrollY());
                invalidate();
            }
        }
        return true;
    }

另外不要忘了重写computeScroll方法

    @Override
    public void computeScroll() {
        //判断滚动时候停止
        if (mScroller.computeScrollOffset()) {
            //滚动到指定的位置
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            //这句话必须写,否则不能实时刷新
            postInvalidate();
        }
    }

剩下的问题就是惯性滑动的添加了,这里需要用到VelocityTracker这个类来计算速度,然后表现到滑动上面,再修改onTouchEvent方法

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
        mGesture.onTouchEvent(event);
        if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
            mVelocityTracker.computeCurrentVelocity(1000, maxFlingVelocity);
            float velocityX = mVelocityTracker.getXVelocity(event.getPointerId(0));
            float velocityY = mVelocityTracker.getYVelocity(event.getPointerId(0));
            completeMove(-velocityX, -velocityY);
            if (mVelocityTracker != null) {
                mVelocityTracker.recycle();
                mVelocityTracker = null;
            }

            if (getScrollY() < 0) {
                mScroller.startScroll(0, getScrollY(), 0, -getScrollY());
                invalidate();
            }
            View lastChild = getChildAt(getChildCount() - 1);
            int bottomY = (int) (lastChild.getY() + lastChild.getMeasuredHeight() - screenHeight);
            if (getScrollY() > bottomY) {
                mScroller.startScroll(0, getScrollY(), 0, bottomY - getScrollY());
                invalidate();
            }
        }
        return true;
    }

最后完成惯性滑动的方法封装到completeMove方法中

    private void completeMove(float v, float velocityY) {
        View lastChild = getChildAt(getChildCount() - 1);
        int bottomY = (int) (lastChild.getY() + lastChild.getMeasuredHeight() - screenHeight);
        mScroller.fling(0, getScrollY(), 0, (int) (velocityY ), 0, getMeasuredWidth(), 0, bottomY);
        invalidate();
    }

你可能感兴趣的:(自定义可以滚动的线性布局)