Android 获取 View 的宽高

154 阅读1分钟

Android 获取 View 的宽高

说明

获取View宽高的方法很多,每一种方法都需要了解他们的具体细节。
常用的方法:
	1.调用view的post方法获取(推荐使用);
	2.view监听视图树的方式获取(会调用多次,不建议使用);
	3.重写 activity 的 onWindowFocusChanged 方法获取(会调用多次,而且fragment中无法使用,不建议使用);

推荐使用方法1

方法1:调用view的post方法获取

xml

<ImageView
	android:id="@+id/ivAnim1"
	android:layout_width="100dp"
	android:layout_height="100dp"
	android:src="@mipmap/img_no_data" />

// post方式
ivAnim1.post(new Runnable() {
	@Override
	public void run() {
		int measuredHeight = ivAnim1.getMeasuredHeight();// 300
		int measuredWidth = ivAnim1.getMeasuredWidth();// 300
		int height = ivAnim1.getHeight();// 300
		int width = ivAnim1.getWidth();// 300
	}
});

方法2:view监听视图树的方式获取

xml

<ImageView
	android:id="@+id/ivAnim1"
	android:layout_width="100dp"
	android:layout_height="100dp"
	android:src="@mipmap/img_no_data" />

	
// onGlobalLayout 方法会回调多次,不建议使用
ViewTreeObserver viewTreeObserver = ivAnim1.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
	@Override
	public void onGlobalLayout() {
		ivAnim1.getViewTreeObserver().removeOnGlobalLayoutListener(this);
		
		int measuredHeight = ivAnim1.getMeasuredHeight();// 300
		int measuredWidth = ivAnim1.getMeasuredWidth();// 300
		int height = ivAnim1.getHeight();// 300
		int width = ivAnim1.getWidth();// 300
	}
});

方法3:重写 activity 的 onWindowFocusChanged 方法获取

注意:该方法只能在activity中使用,fragment中无法使用。
xml

<ImageView
	android:id="@+id/ivAnim1"
	android:layout_width="100dp"
	android:layout_height="100dp"
	android:src="@mipmap/img_no_data" />


/**
 * 每当窗口焦点发生变化时,就会调用此方法,所以会被调用多次
 * activity显示出来的时候调用一次返回true,activity不显示的时候调用一次返回false。
 */
@Override
public void onWindowFocusChanged(boolean hasFocus) {
	super.onWindowFocusChanged(hasFocus);
	if (hasFocus) {
		int measuredHeight = ivAnim1.getMeasuredHeight();// 300
		int measuredWidth = ivAnim1.getMeasuredWidth();// 300
		int height = ivAnim1.getHeight();// 300
		int width = ivAnim1.getWidth();// 300
	}
}