为什么在 onResume() 中的 View 上调用 getWidth() 返回 0? [英] Why does calling getWidth() on a View in onResume() return 0?
本文介绍了为什么在 onResume() 中的 View 上调用 getWidth() 返回 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我读过的所有内容都说您不能在构造函数中的 View
上调用 getWidth()
或 getHeight()
,但是我在 onResume()
中调用它们.那个时候屏幕的布局不应该已经绘制了吗?
@Override受保护的无效 onResume() {super.onResume();填充数据();}私有无效 populateData() {LinearLayout test = (LinearLayout) findViewById(R.id.myview);double widthpx = test.getWidth();}
解决方案
调用 onResume()
时视图仍未绘制,因此其宽度和高度均为 0.您可以当它的大小改变时使用 OnGlobalLayoutListener()
:
yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {@覆盖公共无效 onGlobalLayout() {//移除布局监听器以避免多次调用if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);}别的 {yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);}填充数据();}});
有关其他信息,请查看 Android 获取宽度返回 0.>
Everything I've read says you can't call getWidth()
or getHeight()
on a View
in a constructor, but I'm calling them in onResume()
. Shouldn't the screen's layout have been drawn by then?
@Override
protected void onResume() {
super.onResume();
populateData();
}
private void populateData() {
LinearLayout test = (LinearLayout) findViewById(R.id.myview);
double widthpx = test.getWidth();
}
解决方案
A view still hasn't been drawn when onResume()
is called, so its width and height are 0. You can "catch" when its size changes using OnGlobalLayoutListener()
:
yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Removing layout listener to avoid multiple calls
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
else {
yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
populateData();
}
});
For additional info take a look at Android get width returns 0.
这篇关于为什么在 onResume() 中的 View 上调用 getWidth() 返回 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文