Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

android - Does posting Runnable to an UI thread guarantee that layout is finished when it is run?

First thing! I do know about ViewTreeObserver.onGlobalLayoutListener.

What made me ask this question is the following notice on Android developer documentation website:

The snippet below does the following:

  • Gets the parent view and posts a Runnable on the UI thread. This ensures that the parent lays out its children before calling the getHitRect() method. The getHitRect() method gets the child's hit rectangle (touchable area) in the parent's coordinates.

Snippet itself is:

parentView.post(new Runnable() {
            // Post in the parent's message queue to make sure the parent
            // lays out its children before you call getHitRect()
            @Override
            public void run() {
               /// do UI stuff
            }
});

(you can look at the full article)

So is this a wrong statement or is it true? I am asking because posting a runnable seems easier and more convenient compared to doing all that register-listener/handle-event/unregister-listener dance with ViewTreeObserver :)

UPDATE: One more question to bring clarity to the whole subject: If all this is nice and Runnable can actually be posted instead of using a global layout listener, then why do we have this ViewTreeObserver.onGlobalLayoutListener mechanism at all? When is it better to use it rather than posting a Runnable and what the difference is between this methods?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I like the question too. It forced me to dig into Android source code once again. I believe this works because post() gets called after setContentView().

Method setContentView() ends up in calling ViewGroup.addView() of the top view, and addView() call always triggers requestLayout(). In turn, requestLayout() posts a task to the main thread to be executed later. This task will execute measure and layout on the view hierarchy. Now if you post another task it will be put into the queue after layout task and, as the result, always executed after measure and layout happen. Thus you will always have valid sizes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...