自定义ViewGroup 支持Margin

一般自定义VIewGroup步骤:1.继承ViewGroup2.重写onMeasure3.重写onLayout4.重写onDraw

此时,MarginLayoutParams cParams = (MarginLayoutParams) view1.getLayoutParams();会报异常异常内容为:

java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams

所以要支持Margin还有必须 重写generateLayoutParams方法实例 :

@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)
{
return new MarginLayoutParams(getContext(), attrs);
}

这样就可以支持Margin 进行操作了