2012年3月25日 星期日

[AndroidLayout] getWidth() and getHeight()

Error
當 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:
  1. view.onFinishInflate
  2. view.onMeasure
  3. view.onSizeChanged(width, height, 0, 0)
  4. view.onLayout
  5. 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

沒有留言:

張貼留言