LayoutParams是用来协助Viewgoup的,它可以给子View定义一些属性。而且也可以支持margin。
我们要给子View定义 :
-
从哪里来(from)
-
到哪里去(to)
-
透明度(alpha)
-
缩放值(scale)
所以我们要这样子重写:
/**
- 这里要自己写一个ViewGroup的LayoutParams来记录 scale、alpha、from、to
*/
class RikkaLayoutParams extends MarginLayoutParams {
float scale = 0f;
float alpha = 0f;
int from;
int to;
…(getter and setter)
public RikkaLayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public RikkaLayoutParams(int width, int height) {
super(width, height);
}
public RikkaLayoutParams(LayoutParams source) {
super(source);
}
}
/**
- 要支持margin,所以要重写generate方法
*/
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new RikkaLayoutParams(mContext, attrs);
}
@Override
protected LayoutParams generateLayoutParams(LayoutParams p) {
return new RikkaLayoutParams§;
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new RikkaLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
ViewGroup的宽度要么是写死的值,要么是三个子View之和
高度要么是写死的值,要么是三个View里面,最大的那一个:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//先测量子View
measureChildren(widthMeasureSpec, heightMeasureSpec);
//因为这个时候已经测量完子View了,所以通过子View来计算整个View的宽高
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
//根据获取的宽高拿去用
setMeasuredDimension(width, height);
}
//整个View的宽度是三个子View的和
private int measureWidth(int widthMeasureSpec) {
int totalWidth = 0;
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
totalWidth = widthSize;
} else {
for (int i = 0; i < getChildCount(); i++) {
RikkaLayoutParams lp = (RikkaLayoutParams) getChildAt(i).getLayoutParams();
totalWidth += getChildAt(i).getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
}
}
return totalWidth;
<