有時我們會有基于這樣的需求,當Activity創(chuàng)建時,需要獲取某個View的寬高,然后進行相應的操作,但是我們在onCreate,onStart中獲取View的大小,獲取到的值都是0,只是由于View的繪制工程還未完成,和在onCreate中彈出Dialog或者PopupWindow會報一個Activity not running原理類似。接下來就為大家介紹幾種獲取View寬高的方法
一、重寫Activity中的onWindowFocusChanged,當Activity獲取到焦點的時候View已經繪制完成,也能獲取到View的準確寬高了。同樣的Dialog和PopupWindow也可以在這里彈出,需要注意的是這個方法會調用多次,當hasFocus為true時,才可進行相應的操作
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
System.out.println("onWindowFocusChanged width="
+ tvTest.getWidth() + " height=" + tvTest.getHeight());
}
}
二、
/**
* 會執(zhí)行多次
*/
private void getSize1() {
ViewTreeObserver vto = tvTest.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
int height = tvTest.getMeasuredHeight();
int width = tvTest.getMeasuredWidth();
System.out.println("height" + height);
System.out.println("width" + width);
return true;
}
});
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
三、
private void getSize2() {
ViewTreeObserver viewTreeObserver = tvTest.getViewTreeObserver();
viewTreeObserver
.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
tvTest.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
System.out.println("onGlobalLayout width="
+ tvTest.getWidth() + " height="
+ tvTest.getHeight());
}
});
}
四、
private void getSize3() {
tvTest.post(new Runnable() {
@Override
public void run() {
System.out.println("postDelayed width=" + tvTest.getWidth()
+ " height=" + tvTest.getHeight());
}
});
}
原文地址:http://blog.csdn.net/soul_code/article/details/50474528