如果我在 onResume 中调用 getMeasuredWidth() 或 getWidth() 进行布局,它们将返回 0
如果我在 onResume 中调用 getMeasuredWidth() 或 getWidth() 进行布局,它们将返回 0。 我认为此时此刻还没有绘制出该视图。
另外,我认为我需要将 getMeasuredWidth() 或 getWidth() 放在绘制布局并且视图测量已知后调用的回调方法中。 我应该使用什么android回调方法?
If I call getMeasuredWidth() or getWidth() for layout in onResume they returns 0.
I think that view it's not drawn yet in this moment.
Also I think that I need to put getMeasuredWidth() or getWidth() in callback method called after layout is drawn and view measurements are known.
What android callback method should I use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您不能在之前的
View
上使用width
/height
/getMeasuredWidth
/getMeasuredHeight
系统渲染它(通常来自onCreate
/onResume
)。简单的解决方案是将
Runnable
发布到布局。可运行对象将在View
布局后执行。You cannot use the
width
/height
/getMeasuredWidth
/getMeasuredHeight
on aView
before the system renders it (typically fromonCreate
/onResume
).Simple solution for this is to post a
Runnable
to the layout. The runnable will be executed after theView
has been laid out.这个答案说:
使用
View
上的ViewTreeObserver
来等待对于第一个布局。只有在第一个布局之后,getWidth()/getHeight()/getMeasuredWidth()/getMeasuredHeight()
才会起作用。This answer says:
Use the
ViewTreeObserver
on theView
to wait for the first layout. Only after the first layout willgetWidth()/getHeight()/getMeasuredWidth()/getMeasuredHeight()
work.您可以覆盖
you can override onLayout() in your view; this is used by android to position each of the children the view has, so you could do the stuff you want to do there after the
super(..)
call.事实上,如果布局未显示在屏幕上,则 getWidth() 方法返回 0。对我来说似乎有效的是在调用 getMeasuredWidth() 或 getMesuredHeight() 之前调用measure() 方法。对于测量方法,我使用 Layout.WRAP_CONTENT 参数来测量布局包含的内容。
希望这有帮助,
米哈伊
Indeed, it appears that if the layout is not shown on the screen the getWidth() method returns 0. What seems to work for me is calling the measure() method before calling the getMeasuredWidth() or getMesuredHeight(). For the measure method I used the Layout.WRAP_CONTENT arguments to get a measurement of what the layout contains.
Hope this helps,
Mihai
更简单的方法:
http://developer.android .com/reference/android/view/View.html#post(java.lang.Runnable)
Simpler way:
http://developer.android.com/reference/android/view/View.html#post(java.lang.Runnable)
解决方案#1:
要动态地执行此操作,您需要一个标签。标签基本上是视图拥有记忆的一种方式。因此将convertView保存在另一个类(MyTag)中。
所以在你的java文件中:
解决方案#2:
对其进行硬编码。预设宽度。
在你的 res/values/dimens.xml 文件中,包含
然后在你的 res/layout/your_layout.xml 文件中,包含
然后在你的 java 文件中:
Solution #1:
To do it dynamically, you need a tag. A tag is basically a way for views to have memories. So save the convertView in another class (MyTag).
So inside your java file:
Solution #2:
Hard-code it. Pre-set the width.
Inside your res/values/dimens.xml file, include
Then inside your res/layout/your_layout.xml file, include
Then inside your java file:
使用下面的代码:
Use below code: