自定義可以滾動(dòng)的線(xiàn)性布局

自定義滾動(dòng)的線(xiàn)性布局主要需要完成下面3個(gè)功能

1 計(jì)算子view及本身的尺寸
2 把子view布局到指定的位置
3 添加滑動(dòng)事件

1 計(jì)算尺寸

需要重寫(xiě)下面這個(gè)方法

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

參數(shù)中的widthMeasureSpecheightMeasureSpec是包含寬和高的信息课梳。里面放了測(cè)量模式和尺寸大小但惶,具體獲取方法

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

MeasureSpec.AT_MOST對(duì)應(yīng)布局中的WRAP_CONTENT,MeasureSpec.EXACTLY對(duì)應(yīng)MATCH_PARENT和固定的尺寸,MeasureSpec.UNSPECIFIED指未指定尺寸棘幸,這種情況很少
如果寬高是自適應(yīng)的秸弛、就需要我們自己來(lái)計(jì)算實(shí)際尺寸大小
要實(shí)現(xiàn)可以滾動(dòng)的水平線(xiàn)性布局viewGroup的最大寬度實(shí)際上就是所有子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;
  }

重寫(xiě)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) {
            //我們將高度設(shè)置為所有子View的高度相加柔昼,寬度設(shè)為子View中最大的寬度
            int height = getTotleHeight();
            int width = getMaxChildWidth();
            setMeasuredDimension(width, height);

        } else if (heightMode == MeasureSpec.AT_MOST) {//如果只有高度是包裹內(nèi)容
            //寬度設(shè)置為ViewGroup自己的測(cè)量寬度,高度設(shè)置為所有子View的高度總和
            setMeasuredDimension(widthSize, getTotleHeight());
        } else if (widthMode == MeasureSpec.AT_MOST) {//如果只有寬度是包裹內(nèi)容
            //寬度設(shè)置為子View中寬度最大的值布近,高度設(shè)置為ViewGroup自己的測(cè)量值
            setMeasuredDimension(getMaxChildWidth(), heightSize);

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

尺寸計(jì)算好了垫释,下面就要布局子view了

2 布局子view

實(shí)現(xiàn)起來(lái)很簡(jiǎ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 添加滑動(dòng)事件

添加滑動(dòng)事件就要重寫(xiě)onTouchEvent方法了,可以用手勢(shì)幫助類(lèi)GestureDetector來(lái)實(shí)現(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;
            }
        });
    }

到此吊输,可以滑動(dòng)的線(xiàn)性布局就基本完成了饶号,但是還存在一些缺陷铁追,滑動(dòng)會(huì)超過(guò)邊界季蚂、沒(méi)有慣性滑動(dòng)
首先先來(lái)解決滑動(dòng)超過(guò)邊界的問(wèn)題,思路是在手指抬起的時(shí)候如果滑動(dòng)超過(guò)邊界,就重新滾動(dòng)到邊界扭屁,為了使滑動(dòng)流暢算谈,使用OverScroller實(shí)現(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;
    }

另外不要忘了重寫(xiě)computeScroll方法

    @Override
    public void computeScroll() {
        //判斷滾動(dòng)時(shí)候停止
        if (mScroller.computeScrollOffset()) {
            //滾動(dòng)到指定的位置
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            //這句話(huà)必須寫(xiě),否則不能實(shí)時(shí)刷新
            postInvalidate();
        }
    }

剩下的問(wèn)題就是慣性滑動(dòng)的添加了料滥,這里需要用到VelocityTracker這個(gè)類(lèi)來(lái)計(jì)算速度然眼,然后表現(xiàn)到滑動(dòng)上面,再修改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;
    }

最后完成慣性滑動(dòng)的方法封裝到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();
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市葵腹,隨后出現(xiàn)的幾起案子高每,更是在濱河造成了極大的恐慌,老刑警劉巖践宴,帶你破解...
    沈念sama閱讀 222,729評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鲸匿,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡阻肩,警方通過(guò)查閱死者的電腦和手機(jī)带欢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)烤惊,“玉大人乔煞,你說(shuō)我怎么就攤上這事∑馐遥” “怎么了渡贾?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,461評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)雄右。 經(jīng)常有香客問(wèn)我剥啤,道長(zhǎng),這世上最難降的妖魔是什么不脯? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,135評(píng)論 1 300
  • 正文 為了忘掉前任府怯,我火速辦了婚禮,結(jié)果婚禮上防楷,老公的妹妹穿的比我還像新娘牺丙。我一直安慰自己,他們只是感情好复局,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,130評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布冲簿。 她就那樣靜靜地躺著,像睡著了一般亿昏。 火紅的嫁衣襯著肌膚如雪峦剔。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,736評(píng)論 1 312
  • 那天角钩,我揣著相機(jī)與錄音吝沫,去河邊找鬼呻澜。 笑死,一個(gè)胖子當(dāng)著我的面吹牛惨险,可吹牛的內(nèi)容都是我干的羹幸。 我是一名探鬼主播,決...
    沈念sama閱讀 41,179評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼辫愉,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼栅受!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起恭朗,我...
    開(kāi)封第一講書(shū)人閱讀 40,124評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤屏镊,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后痰腮,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體闸衫,經(jīng)...
    沈念sama閱讀 46,657評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,723評(píng)論 3 342
  • 正文 我和宋清朗相戀三年诽嘉,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蔚出。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,872評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡虫腋,死狀恐怖骄酗,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情悦冀,我是刑警寧澤趋翻,帶...
    沈念sama閱讀 36,533評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站盒蟆,受9級(jí)特大地震影響踏烙,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜历等,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,213評(píng)論 3 336
  • 文/蒙蒙 一讨惩、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧寒屯,春花似錦荐捻、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,700評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至菩掏,卻和暖如春魂角,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背智绸。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,819評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工野揪, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留访忿,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,304評(píng)論 3 379
  • 正文 我出身青樓囱挑,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親沼溜。 傳聞我的和親對(duì)象是個(gè)殘疾皇子平挑,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,876評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容