4种Android获取View宽高的方式
有时我们会有基于这样的需求,当Activity创建时,需要获取某个View的宽高,然后进行相应的操作,但是我们在onCreate,onStart中获取View的大小,获取到的值都是0,只是由于View的绘制工程还未完成,和在onCreate中弹出Dialog或者PopupWindow会报一个Activitynotrunning原理类似。
接下来就为大家介绍几种获取View宽高的方法:
第一种方式:重写Activity中的onWindowFocusChanged,当Activity获取到焦点的时候View已经绘制完成,也能获取到View的准确宽高了。同样的Dialog和PopupWindow也可以在这里弹出,需要注意的是这个方法会调用多次,当hasFocus为true时,才可进行相应的操作
@Override
publicvoidonWindowFocusChanged(booleanhasFocus){
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
System.out.println("onWindowFocusChangedwidth="
+tvTest.getWidth()+"height="+tvTest.getHeight());
}
}
第二种方式:
/**
*会执行多次
*/
privatevoidgetSize1(){
ViewTreeObservervto=tvTest.getViewTreeObserver();
vto.addOnPreDrawListener(newViewTreeObserver.OnPreDrawListener(){
@Override
publicbooleanonPreDraw(){
intheight=tvTest.getMeasuredHeight();
intwidth=tvTest.getMeasuredWidth();
System.out.println("height"+height);
System.out.println("width"+width);
returntrue;
}
});
}
第三种方式:
privatevoidgetSize2(){
ViewTreeObserverviewTreeObserver=tvTest.getViewTreeObserver();
viewTreeObserver
.addOnGlobalLayoutListener(newOnGlobalLayoutListener(){
@Override
publicvoidonGlobalLayout(){
tvTest.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
System.out.println("onGlobalLayoutwidth="
+tvTest.getWidth()+"height="
+tvTest.getHeight());
}
});
}
第四种方式:
privatevoidgetSize3(){
tvTest.post(newRunnable(){
@Override
publicvoidrun(){
System.out.println("postDelayedwidth="+tvTest.getWidth()
+"height="+tvTest.getHeight());
}
});
}
以上就是Android获取View宽高的4种方式,希望对大家的学习有所帮助。
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短