使用一個view的getWidth() getHeight() 方法來獲取該view的寬和高,返回的值卻為0。如果這個view的長寬很確定不為0的話,那很可能是你過早的調用這些方法,也就是說在這個view被加入到rootview之前你就調用了這些方法,返回的值自然為0.
解決該問題的方法有很多,主要就是延後調用這些方法。可以試著在onWindowFocusChanged()裡面調用這些方法。
以下是stack overflow中的回答。
Anyhow, the deal is that layout of the contents of a window happens after all the elements are constructed and added to their parent views. It has to be this way, because until you know what components a View contains, and what they contain, and so on, there's no sensible way you can lay it out.
Bottom line, if you call getWidth() etc. in a constructor, it will return zero. The procedure is to create all your view elements in the constructor, then wait for your View's onSizeChanged() method to be called -- that's when you first find out your real size, so that's when you set up the sizes of your GUI elements.
Be aware too that onSizeChanged() is sometimes called with parameters of zero -- check for this case, and return immediately (so you don't get a divide by zero when calculating your layout, etc.). Some time later it will be called with the real values.