获取view的高和宽

在有些地方,如onCreate或者listAdapter的getView里,view未绘制,那么无法通过调用getHeight或者getHeight来获取view的尺寸。view在显示之前需要经过measure和requestLayout的步骤,也就是在显示前需要被测量。因此可以通过如下方法来获得view尺寸:

	public static int getWidth(View v){
		int width = View.MeasureSpec.makeMeasureSpec(0,
		        View.MeasureSpec.UNSPECIFIED);
		int height = View.MeasureSpec.makeMeasureSpec(0,
		        View.MeasureSpec.UNSPECIFIED);
		v.measure(width, height);
		return v.getMeasuredWidth();
	}



	public static int getHeight(View v){
		int width = View.MeasureSpec.makeMeasureSpec(0,
		        View.MeasureSpec.UNSPECIFIED);
		int height = View.MeasureSpec.makeMeasureSpec(0,
		        View.MeasureSpec.UNSPECIFIED);
		v.measure(width, height);
		return v.getMeasuredHeight();
	}


你可能感兴趣的:(android,MeasureSpec)