Android获取View的宽度和高度

onCreate onStart onResume都不能直接获得View的宽度高度,因为View的绘制并不是和Activity的生命周期同步进行的。

解决方法:

1

onWindowFocusChanged

当Activity失去获得焦点的时候,说明View已经绘制完了,因此可以获得宽度高度。

e.g.

public void onWindowFocusChanged(boolean hasFocus){
	super.onWindowFocusChanged(hasFocus);
	if(hasFocus){
		int width = view.getMeasuredWidth();
		int height = view.getMeasuredHegiht();
	}
}

2

view.post(runnable)

post可以将runnable投递到消息队列的尾部,然后等待Looper调用runnable的时候,view已经初始化好了。

e.g.

protected void onStart(){
	super.onStart();
	view.post(new Runnable(){
		public void run(){
			int width = view.getMeasuredWidth();
			int height = view.getMeasuredHegiht();
			
		}
	});
}

3

ViewTreeObserver

View树的状态或者可见性发生改变的时候回回调onGlobalLayout方法,因此是获得View的高宽度的好时机。

e.g.

protected void onStart(){
	super.onStart();
	ViewTreeObserver observer = view.getViewTreeObserver();
	observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
		public void onGlobalLayout(){
			view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
			int width = view.getMeasuredWidth();
			int height = view.getMeasuredHegiht();
		}
	});
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值