文章目录
自定义ViewGroup添加View时对View对应的LayoutParams的处理操作
Android 7只需要重写ViewGroup的generateLayoutParams方法,创建需要的LayoutParmas
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
Android 15 需要重写ViewGroup的generateLayoutParams方法和
generateDefaultLayoutParams方法
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
小结
如果要自定义ViewGroup,对添加到其中的View对应LayoutParams有特殊要求(如需要是MarginLayoutParams),需要重写ViewGroup.generateDefaultLayoutParams()和ViewGroup.generateLayoutParams()来保证各个版本都没有问题