@Override protectedvoidonMeasure(int widthMeasureSpec, int heightMeasureSpec){ super.onMeasure(widthMeasureSpec, heightMeasureSpec); int measuredWidth = 0; int measuredHeight = 0; finalint childCount = getChildCount(); measureChildren(widthMeasureSpec, heightMeasureSpec);////measure all children view width and height.
int widthSpaceSize = MeasureSpec.getSize(widthMeasureSpec); int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int heightSpaceSize = MeasureSpec.getSize(heightMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); if (childCount == 0) {// If ViewGroup has not child, the size of viewGroup will be 0 setMeasuredDimension(0, 0); } elseif (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {//Handle wrap_content final View childView = getChildAt(0); measuredWidth = childView.getMeasuredWidth() * childCount; measuredHeight = childView.getMeasuredHeight(); setMeasuredDimension(measuredWidth, measuredHeight); } elseif (widthSpecMode == MeasureSpec.AT_MOST) { final View childView = getChildAt(0); measuredWidth = childView.getMeasuredWidth() * childCount; setMeasuredDimension(measuredWidth, heightSpaceSize); } elseif(heightSpecMode == MeasureSpec.AT_MOST){ final View childView = getChildAt(0); measuredHeight = childView.getMeasuredHeight(); setMeasuredDimension(widthSpaceSize, measuredHeight); } }
onLayout()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
@Override protectedvoidonLayout(boolean changed, int l, int t, int r, int b){ int childLeft = 0; finalint childCount = getChildCount(); mChildrenSize = childCount;
for (int i = 0; i < childCount; i++) {//Traverse all child and put them at a right place final View childView = getChildAt(i); if (childView.getVisibility() != View.GONE) { finalint childWidth = childView.getMeasuredWidth(); mChildWidth = childWidth; childView.layout(childLeft, 0, childLeft + childWidth, childView.getMeasuredHeight());//(l,t,r,b) childLeft += childWidth; } } }