1. 程式人生 > >從原始碼角度解析 - ScrollView巢狀ListView只顯示一行的問題

從原始碼角度解析 - ScrollView巢狀ListView只顯示一行的問題

<ScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation
="vertical">
<ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> </ScrollView>

上面的佈局在預設情況下,是達不到我們想到的效果,只會顯示ListView的一行內容,同樣的我們可以通過反推的方式,來查詢原因的所在。
為何只會顯示一行??我們可以先看看ListView的onMeasure方法

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Sets up mListPadding
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int
widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int childWidth = 0; int childHeight = 0; int childState = 0; mItemCount = mAdapter == null ? 0 : mAdapter.getCount(); if (mItemCount > 0 && (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED)) { final View child = obtainView(0, mIsScrap); // Lay out child directly against the parent measure spec so that // we can obtain exected minimum width and height. measureScrapChild(child, 0, widthMeasureSpec, heightSize); childWidth = child.getMeasuredWidth(); childHeight = child.getMeasuredHeight(); childState = combineMeasuredStates(childState, child.getMeasuredState()); if (recycleOnMeasure() && mRecycler.shouldRecycleViewType( ((LayoutParams) child.getLayoutParams()).viewType)) { mRecycler.addScrapView(child, 0); } } if (widthMode == MeasureSpec.UNSPECIFIED) { widthSize = mListPadding.left + mListPadding.right + childWidth + getVerticalScrollbarWidth(); } else { widthSize |= (childState & MEASURED_STATE_MASK); } //當高度的測量模式為UNSPECIFIED,此時的ListView的高度就是一行的高度 if (heightMode == MeasureSpec.UNSPECIFIED) { heightSize = mListPadding.top + mListPadding.bottom + childHeight + getVerticalFadingEdgeLength() * 2; } if (heightMode == MeasureSpec.AT_MOST) { // TODO: after first layout we should maybe start at the first visible position, not 0 heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1); } setMeasuredDimension(widthSize, heightSize); mWidthMeasureSpec = widthMeasureSpec; }

從原始碼上可以看出,只有當高度的測量模式為UNSPECIFIED,此時的ListView的高度heightSize 就是一行的高度,所以我們要想辦法讓程式不進入if (heightMode == MeasureSpec.UNSPECIFIED)這個語句內,而是進入if (heightMode == MeasureSpec.AT_MOST)這個語句內,measureHeightOfChildren方法才是測量統計所有的Item高度的實現

關於程式是如何進入if (heightMode == MeasureSpec.UNSPECIFIED)內的,我們可以從ScrollView的onMeasure方法中得知
我們知道ViewGroup的measure測量過程是一個遞迴過程,它會在父元素中的onMeasure方法中,遍歷所有的子元素進行對子元素逐個measure測量,而父元素的測量規格MeasureSpec同時也會影響到子元素的測量規格MeasureSpec;我們可以從ScrollView的onMeasure原始碼可以看出

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

        if (!mFillViewport) {
            return;
        }

        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode == MeasureSpec.UNSPECIFIED) {
            return;
        }
 ……省略
 }

我們進入super.onMeasure方法中,再去看看具體

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();

        final boolean measureMatchParentChildren =
                MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
                MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
        mMatchParentChildren.clear();

        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
              //這個方法很重要,是用測量子view的大小
               measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);

                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
                childState = combineMeasuredStates(childState, child.getMeasuredState());
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        mMatchParentChildren.add(child);
                    }
                }
            }
        }
        ……省略
}

從上面的原始碼可以看出,ScrollView的onMeasure方法內通過for迴圈遍歷子view,通過measureChildWithMargins方法來實現子View的測量工作,我們再點進measureChildWithMargins方法內看看細節

protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

從上面的程式碼可知,會根據父元素的parentWidthMeasureSpec、parentHeightMeasureSpec的測量規格,得到子元素的childWidthMeasureSpec 、childHeightMeasureSpec 測量規格,在其過程中並未改變子元素的測量模式,其實這時候我們看到measureChildWithMargins這個方法是ViewGroup的標準測量過程,而ScrollView已經對measureChildWithMargins方法進行重寫了,接下來看看ScrollView的重寫後的measureChildWithMargins方法

  @Override
    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

從原始碼可知,在構建子元素的高度測量規格childHeightMeasureSpec 時,已經把子元素的測量模式設定成了UNSPECIFIED模式了,此時在回頭看看ListView的onMeasure方法,就知道為何會進入if (heightMode == MeasureSpec.UNSPECIFIED)內,接下來我們可以通過重寫ListView的onMeasure方法,進行修改heightMeasureSpec的測量模式來解決只顯示一行的問題,如下:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //問題是解決下,但缺點也是很明細,就是ListView的複用機制不起作用了
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE << 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

在makeMeasureSpec方法中,size未必就是Integer.MAX_VALUE << 2,只要測量值的範圍內即可,越大越好。