private int calculatedWidth;
private int calculatedHeight;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {//此方法用于计算视图的尺寸
Log.d("view test", "onmeasure - " + getWidth() + " - " + getHeight()
+ " -/n/r - " + getMeasuredWidth() + " - "
+ getMeasuredHeight());
if (getMeasuredWidth() == 0 || getMeasuredHeight() == 0) {//第一次系统计算尺寸为0,即系统还未计算,先调用父类进行计算(viewgroup及其子类会//根据其中的子视图计算出最大的尺寸)
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// for (int i = 0; i < getChildCount(); i++) {
// View v = getChildAt(i);
// Log.d("view test",
// "child view - " + i + " - size - " + v.getMeasuredWidth()
// + " - " + v.getMeasuredHeight());
// }
int width = 0;
int height = 0;
if (calculatedWidth == 0 || calculatedHeight == 0) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);//得到横向计算模式
int widthSize = MeasureSpec.getSize(widthMeasureSpec);//得到横向最大尺寸
int heightMode = MeasureSpec.getMode(heightMeasureSpec);//得到竖向计算模式
int heightSize = MeasureSpec.getSize(heightMeasureSpec);//得到竖向最大尺寸
FontMetrics fm = titlePaint.getFontMetrics();
float textHeight = fm.descent - fm.ascent;
float temp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
2, getResources().getDisplayMetrics());
Log.d("view test", "size - " + widthSize + " - " + heightSize);
if (widthMode == MeasureSpec.EXACTLY) {//最大化模式,即match_parent
width = widthSize;
} else {//wrap_content等
int desired = (int) (getPaddingLeft() + getMeasuredWidth()
+ temp + getPaddingRight());
Log.d("view test", "width desire - " + desired);
width = desired;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
int desired = (int) (getPaddingTop() + textHeight
+ getMeasuredHeight() + temp + getPaddingBottom());
Log.d("view test", "height desire - " + desired);
height = desired;
}
this.calculatedWidth = width;
this.calculatedHeight = height;
} else {
width = calculatedWidth;
height = calculatedHeight;
}
setMeasuredDimension(width, height);//将自己计算的尺寸设置给视图
}
安卓自定义view学习_2
最新推荐文章于 2021-02-24 23:16:30 发布