有时我们需要在Activity中获取某个View的宽高,但是在onCreate(),onStart(),onResume()中使用view.getHeight()和view.getWidth()方法获取View的宽高,获取到的值竟然都是0,是不是很无语,
这里给出几种获取View宽高的方法
//第一种
<span style="white-space:pre"> </span>@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
int height = view.getHeight();
int width = view.getWidth();
Log.e("onWindowFocusChanged-------", " width=" + width + " height="
+ height);
}
}
//第二种,会执行很多次
private void getViewSize(final View view) {
<span style="white-space:pre"> </span>ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
int height = view.getMeasuredHeight();
int width = view.getMeasuredWidth();
Log.e("OnPreDraw-------", " width=" + width + " height="+ height);
return true;
}
});
}
//第三种
private void getViewSize2(final View view) {
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver
.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
int width = view.getWidth();
int height = view.getHeight();
Log.e("onGlobalLayout-------", " width=" + width
+ " height=" + height);
}
});
}
//第四种
private void getViewSize3(final View view) {
<span style="white-space:pre"> </span>view.post(new Runnable() {
<span style="white-space:pre"> </span>@Override
public void run() {
int width = view.getWidth();
int height = view.getHeight();
Log.e("postRunnable-------", " width=" + width + " height="+ height);
}
});
}