由网友(青)分享简介:我读过的一切说,你不能叫的getWidth()或的getHeight()在查看在构造函数中,但我打电话给他们在 onResume()。不应在屏幕的布局已经被绘制话? @覆盖保护无效onResume(){ super.onResume(); populateData();}私人无效populateData(...![为什么C 程序无法引用自己写的头文件](https://p.xsw88.cn/allimgs/daicuo/20230906/1795.png)
我读过的一切说,你不能叫的getWidth()
或的getHeight()
在查看
在构造函数中,但我打电话给他们在 onResume()
。不应在屏幕的布局已经被绘制话?
@覆盖保护无效onResume(){ super.onResume(); populateData();}私人无效populateData(){ 测试的LinearLayout =(的LinearLayout)findViewById(R.id.myview); 双widthpx = test.getWidth();}
解决方案
一个观点仍没有绘制时onResume被调用,所以它的宽度和高度都为0。你可以捕捉时,它的大小使用OnGlobalLayoutListener改变() 。 的Android得到回报宽度0 可能会有所帮助。
yourView.getViewTreeObserver()。addOnGlobalLayoutListener(新OnGlobalLayoutListener(){ @覆盖 公共无效onGlobalLayout(){ //删除布局监听器,以避免多次调用 如果(Build.VERSION.SDK_INT< Build.VERSION_ codeS.JELLY_BEAN){ 。yourView.getViewTreeObserver()removeGlobalOnLayoutListener(本); } 其他{ 。yourView.getViewTreeObserver()removeOnGlobalLayoutListener(本); } populateData(); }});
![为什么C 程序无法引用自己写的头文件](https://p.xsw88.cn/allimgs/daicuo/20230906/1795.png)
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 drawn when onResume is called, so its width and height are 0. You can "catch" when its size changed using OnGlobalLayoutListener(). Android get width returns 0 might be helpful.
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();
}
});
相关推荐
最新文章