最常用的解决方式

1
2
3
4
5
6
7
view.post(new Runnable() {
@Override
public void run() {
int width = view.getWidth();
int height = view.getHeight();
}
});

原理:

  • 当 View 还没 attachedToWindow 时,会先将这些 Runnable 操作缓存下来。

  • 如果 View.post(Runnable) 的 Runnable 操作没有被缓存下来,就直接通过 mAttachInfo.mHandler 将这些 Runnable 操作 post 到主线程的 MessageQueue 中等待执行。

  • 如果 View.post(Runnable) 的 Runnable 操作被缓存下来了,那么这些操作将会在 dispatchAttachedToWindow() 被回调时,通过 mAttachInfo.mHandler.post() 发送到主线程的 MessageQueue 中等待执行。

参考文章

android 开发 在oncreate()中获取到控件的高度和宽度值为0解决办法