在android开发中,系统自带的Layout不一定能满足我们的需求,这时候就需要自定义ViewGroup了,自定义的时候需要注意三点:
1.构造函数
构造函数最好三个都要实现
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
}
2.实现函数onMeasure
这个函数用于通过两个方面来确定自己的大小
1)传递进来的参数
2)子控件的大小
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureChildren(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(mWidth, mHeight);
}
3.实现函数onLayout
在该函数中需要对自子控件的位置进行布局
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int count = getChildCount();
for ( int i = 0; i < count; ++i ) {
View v = this.getChildAt(i);
LayoutParams lp = (LayoutParams)v.getLayoutParams();
v.layout(lp.mX, lp.mY, lp.mX + lp.width, lp.mY + lp.height);
}
}