楼主最近在复习自定义View,在复习到自定义ViewGroup这个知识点时,发现了一个问题--就是我们之前的定义ViewGroup在考虑Margin属性可能有问题。本文在解决该问题给出建议性的意见,但是不一定是正确的,如果有错误或者不当的地方,希望指正。
本文参考文章:
1.Android 手把手教您自定义ViewGroup(一)
2.你的自定义View是否真的支持Margin
1.提出问题
这里我举一个简单的例子来说,假设我们需要定义一个ViewGroup放置一个子View,同时这个子View支持Padding和Margin属性。
这里我先贴出一个常规的写法:
public class CustomViewGroup02 extends ViewGroup {
public CustomViewGroup02(Context context) {
super(context);
}
public CustomViewGroup02(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomViewGroup02(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//这里假设只有一个子View
measureChildren(widthMeasureSpec, heightMeasureSpec);
View view = getChildAt(0);
MarginLayoutParams lp = (MarginLayoutParams) view.getLayoutParams();
int width = view.getMeasuredWidth() + lp.leftMargin + lp.rightMargin + getPaddingLeft() + getPaddingRight();