Timing of ListView Layout Pass (how to keep a layout pass from running while changing the dataset?)

孤街醉人 提交于 2019-12-12 01:33:26

问题


An answer to another question raised a different question for me.

When displaying a ListView you update the Data Set then call the adapter's notifyDataSetChanged(). This calls requestLayout() and the Google documentation says "This will schedule a layout pass of the view tree"

So apparently we don't really know when that will take place. But during the layout pass many of the custom overrides in the adapter such as getView() and getCount() will be accessing the data set. So if the layout pass is run at an unknown time how do you know when it's safe to alter the data set?

I have a complex data set with multiple arrays that I need to keep synchronized with each other so I make my changes and call notifyDataSetChanged(). After that I may need to make more changes (say, because new data has come in over the network) so how do I make sure a layout pass from the previous notifyDataSetChanged() isn't going to run in the middle of making the new changes?

Also, what does Google mean by "schedule" a layout pass? When I log stuff in getView() the TID shown in the Logcat screen is the same as the main UI thread. so after calling notifyDataSetChanged() if I check for new data and start updating my arrays how does Android manage to run the layout pass in that same thread?


回答1:


So if the layout pass is run at an unknown time how do you know when it's safe to alter the data set?

It's very simple: by only updating the data set in the UI thread, you're guaranteed to avoid any problems. Since the layout also occurs in the UI thread, both operations will, by necessity, execute serially. This can be achieved via AsyncTask, Handler, or any other method of thread communication.

Also, what does Google mean by "schedule" a layout pass?

A message is posted for the UI thread's Looper. It will be processed whenever said thread is idle.



来源:https://stackoverflow.com/questions/23892736/timing-of-listview-layout-pass-how-to-keep-a-layout-pass-from-running-while-cha

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