Skip to content

Instantly share code, notes, and snippets.

@boxme
Forked from ixiyang/gist:7922825
Created April 18, 2016 10:11
Show Gist options
  • Save boxme/659843a26e90ab76629128668bd8b97c to your computer and use it in GitHub Desktop.
Save boxme/659843a26e90ab76629128668bd8b97c to your computer and use it in GitHub Desktop.
difference between requestLayout() and forceLayout()
比喻很形象
Please note that the methods in Listing 1-10 are internal methods and are not part of the
public API, so they may change with newer releases. However, the underlying protocol would remain
the same.
In Listing 1-10, it is easier to first tell what forceLayout( ) is. It is like a touch command in build
environments. Usually when a file hasn’t changed, the build dependencies will ignore it. So, you
force that file to be compiled by “touch”ing, and thereby updating its time stamp. Just like touch,
the forceLayout( ) will not invoke any build commands by itself (unless your build environment is too
sophisticated to kick off right away). The effect of touch is that, when a build is requested, you don’t
ignore this file.
So, when you forceLayout( ) a view, you are marking that view (only that one) as a candidate for
measuring. If a view is not marked, then its onMeasure( ) will not be called. You can see this in the
measure( ) method of the view. The measure( ) method checks to see if this view is marked for layout.
The behavior of requestLayout( ) is (only) slightly different. A requestlayouttouches the current
view as does forceLayout( ), but it also walks up the chain touching every parent of this view until it
reaches ViewRoot. ViewRootoverrides this method and schedules a layout pass. Because it is just a
schedule to run, it doesn’t start the layout pass right away. It waits for the main thread to complete
its chores and attend the message queue.
懒得看比喻,这里是结论
If a target view is changing size, and if you believe the size of your sibling view will get impacted,
then call requestLayouton yourself and call forceLayouton your sibling. Of course, you can call the
siblings requestLayoutas well, but that adds a few more cycles to the CPU; if youknow what you
are doing, a simpler forceLayoutwould do the trick. It is possibly also common in complex layouts
that are derived from view groups, where a change to a single sibling may need a measurement of its
siblings, so you want to explicitly decide if they need to remeasure again or not.
From expert android
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment