安卓自定义ViewGroup(加上了内外边距)

时间:2024-10-09 07:16:11
  • @Override
  • protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {//这个方法测量出当前自定义View所需要的宽高
  • super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  • int widthMode = (widthMeasureSpec);
  • int heightMode = (heightMeasureSpec);
  • int widthSize = (widthMeasureSpec);
  • int heightSize = (heightMeasureSpec);
  • (TAG, "widthSize=" + widthSize);
  • (TAG, "heightSize=" + heightSize);
  • int width = 0;
  • int height = 0;
  • int childCount = getChildCount();
  • for (int i = 0; i < childCount; i++) {
  • View child = getChildAt(i);
  • measureChild(child, widthMeasureSpec, heightMeasureSpec);//这里非常重要千万别搞错
  • MarginLayoutParams lp = (MarginLayoutParams) ();
  • int measuredWidth = () + + ;//子View的宽需要加上左右边距
  • int measuredHeight = () + + ;//子View的高需要加上下边距
  • (TAG, "measuredWidth=" + measuredWidth);
  • (TAG, "measuredHeight=" + measuredHeight);
  • width = (width, measuredWidth);
  • height += measuredHeight;
  • }
  • width += getPaddingLeft() + getPaddingRight();//这里需要加上自己的左右内边距
  • height += getPaddingTop() + getPaddingBottom();//这里需要加上自己的上下内边距
  • (TAG, "width=" + width);
  • (TAG, "height=" + height);
  • setMeasuredDimension(widthMode == ? widthSize : width, heightMode == ? heightSize : height);
  • }