自定義可以滾動的線性布局

自定義滾動的線性布局主要需要完成下面3個功能

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

1 計算尺寸

需要重寫下面這個方法

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

參數(shù)中的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指未指定尺寸,這種情況很少
如果寬高是自適應的、就需要我們自己來計算實際尺寸大小
要實現(xiàn)可以滾動的水平線性布局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);
        //如果寬高都是包裹內(nèi)容
        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) {//如果只有高度是包裹內(nèi)容
            //寬度設置為ViewGroup自己的測量寬度,高度設置為所有子View的高度總和
            setMeasuredDimension(widthSize, getTotleHeight());
        } else if (widthMode == MeasureSpec.AT_MOST) {//如果只有寬度是包裹內(nèi)容
            //寬度設置為子View中寬度最大的值,高度設置為ViewGroup自己的測量值
            setMeasuredDimension(getMaxChildWidth(), heightSize);

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

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

2 布局子view

實現(xiàn)起來很簡單

    @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來實現(xiàn)

    @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實現(xiàn),修改之前的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這個類來計算速度,然后表現(xiàn)到滑動上面,再修改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();
    }
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容