1. 程式人生 > >自定義viewGroup childView的測量寬度時出現偏差 http://blog.csdn.net/u011102153/article/details/52245312

自定義viewGroup childView的測量寬度時出現偏差 http://blog.csdn.net/u011102153/article/details/52245312

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);
}
protected void measureChild(View child, int parentWidthMeasureSpec,
        int parentHeightMeasureSpec) {
    final LayoutParams lp = child.getLayoutParams();


    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
            mPaddingTop + mPaddingBottom, lp.height);


    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);

}

原始碼很簡短,主要區別是measureChildWithMargins得到子控制元件的MarginLayoutParams ,在呼叫getChildMeasureSpec時傳入了lp.leftMargin, lp.rightMargin, 

這樣就很好解釋出錯的測量寬度剛好比正確時的測量寬度多一個lp.leftMargin和一個lp.rightMargin了。
<code class="language-java hljs  has-numbering" style="display: block; padding: 0px; background: transparent; color: inherit; box-sizing: border-box; font-family: "Source Code Pro", monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal;"></code>