安卓自定义view学习_2

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);//将自己计算的尺寸设置给视图
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值