@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { measureChildren(widthMeasureSpec, heightMeasureSpec); int specModeW = MeasureSpec.getMode(widthMeasureSpec); int specSizeW = MeasureSpec.getSize(widthMeasureSpec); int specModeH = MeasureSpec.getMode(heightMeasureSpec); int specSizeH = MeasureSpec.getSize(heightMeasureSpec); int maxWidth = specSizeW; int maxHeight = specSizeH; int maxChildHeight = 0; int totalWidth = mOffsetLeft; for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); final ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) child.getLayoutParams(); int vHeight = child.getMeasuredHeight() + lp.bottomMargin + lp.topMargin; int vWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin; maxChildHeight = Math.max(maxChildHeight, vHeight); totalWidth += vWidth; } ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) getLayoutParams(); totalWidth += lp.leftMargin + lp.rightMargin; maxChildHeight += lp.topMargin + lp.bottomMargin; if (specModeH == MeasureSpec.UNSPECIFIED) { maxHeight = maxChildHeight; } else if (specModeH == MeasureSpec.AT_MOST) { maxHeight = Math.min(maxHeight, maxChildHeight); } maxWidth = Math.max(specSizeW, totalWidth); setMeasuredDimension(maxWidth, maxHeight); }