The bottom line is that by posting a runnable
, you wait for the queued UI changes to finish so that the view is updated and idle.
Case 1: You are trying to access parts of the views at some point when they are not available yet eg. You want the size of the layout in the onCreate()
, the view has been initialized but not measured or drawn. In such case, you want to execute the code when the view is drawn and ready. By posting a runnable
on the UI thread, you are delaying the execution of the code till that view is drawn and ready.
Case 2:
Many API
calls in Android cause the view/layout
to change and redrawn. For eg. calling notifyDataSetChanged()
will redraw the list items. Android doesn't draw it right away, but waits for the UI thread to be idle (someething like posting a runnable on the UI thread). In such cases, if you call method A
which performs some action on the list, then the values returned may not be accurate as the changed view has not been drawn or layout yet. In such cases you post a runnable
, which executes after the UI queue has completed (which basically means the changed view has been drawn)