當 view 還未完整被 layout 前,呼叫 getWidth() and getHeight() 所得的值會是 0。
Solution
- The view's size is assigned when view.onSizeChanged is called with oldw = oldh = 0.
- Assuming your view is visible, its size has been assigned by the time the activity's window receives focus. That is, when activity.onWindowFocusChanged is called with hasFocus = true.
The sequence is roughly:
- view.onFinishInflate
- view.onMeasure
- view.onSizeChanged(width, height, 0, 0)
- view.onLayout
- activity.onWindowFocusChanged(true)
// 這樣能確保得到正確的 width and height. view.post(new Runnable() { // TODO });
* Reference
- Re: When are View.getWidth and getHeight values valid? - joebowbeer - com.googlegroups.android-developers - MarkMail