Why does onLayout and onSizeChanged get called twice on an orientation change?

吃可爱长大的小学妹 提交于 2019-12-01 03:20:50

I've been wondering this myself for a very long time.

The way I answered the question--because I do believe the answer is, it depends--is by adding a try/catch or logging statement in the requestLayout method. This allows you to see when the requests for remeasuring and re-laying out are made, and in the case of the try/catch, by whom.

The way laying out in Android works is that you mark a view as having a dirty layout with requestLayout. An Android looper which always runs on the UI thread on some interval will remeasure and re-layout views in the tree that have been marked as dirty at some indeterminate point in the future.

I venture to guess that onConfigurationChanged, you are getting several requestLayout calls and the looper is calling onMeasure somewhere in the middle of them.

This is what the logging looked like for me:

11-07 15:39:13.624: W/YARIAN(30006): requestLayout
11-07 15:39:13.632: W/YARIAN(30006): requestLayout
11-07 15:39:13.640: W/YARIAN(30006): requestLayout
11-07 15:39:13.647: W/YARIAN(30006): requestLayout
11-07 15:39:13.686: W/YARIAN(30006): requestLayout
11-07 15:39:13.718: W/YARIAN(30006): requestLayout
11-07 15:39:13.827: W/YARIAN(30006): requestLayout
11-07 15:39:14.108: W/YARIAN(30006): onLayout
11-07 15:39:14.155: W/YARIAN(30006): requestLayout
11-07 15:39:14.272: W/YARIAN(30006): onLayout

The Android documentation has more information on measuring and laying out, but is sadly short on the specifics I described above.

Event Handling and Threading

The basic cycle of a view is as follows:

  1. An event comes in and is dispatched to the appropriate view. The view handles the event and notifies any listeners.
  2. If in the course of processing the event, the view's bounds may need to be changed, the view will call requestLayout().
  3. Similarly, if in the course of processing the event the view's appearance may need to be changed, the view will call invalidate().
  4. If either requestLayout() or invalidate() were called, the framework will take care of measuring, laying out, and drawing the tree as appropriate.

Note: The entire view tree is single threaded. You must always be on the UI thread when calling any method on any view. If you are doing work on other threads and want to update the state of a view from that thread, you should use a Handler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!