Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

android - Why is requestLayout being called directly after invalidate

I'm learning about custom views and wanted to learn about invalidate() and requestLayout().

Please refer to this answer and its diagram:

https://stackoverflow.com/a/25846243/4243687

invalidate() tells Android that the state of the view has changed and needs to be re-drawn.

requestLayout() means the size of the view may have changed and needs to be remeasured, and then re-drawn.

invalidate() will invoke dispatchDraw(), draw(), and onDraw() hence it re-renders the view.

requestLayout() on the other hand does pretty much everything from measuring to re-rendering again.

Why do so many of the examples out there (even the TextView source code) call invalidate() and then requestLayout() right on the next line?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

invalidate() is used specifically for redrawing the content of your view. The redraw does not happen synchronously. Instead, it flags the region of your view as invalid so that it will be redrawn during the next render cycle.

requestLayout() should be used when something within it has possibly changed its dimensions. In this case, the parent view and all other parents up the view hierarchy will need to readjust themselves via a layout pass.

If you are not doing anything to your view that would change its size, then you do not have to call requestLayout().

If you go back and look at the places in the code for TextView where requestLayout() is being called, it will be on methods where the view's bounds will be affected. For example, setPadding(), setTypeface(), setCompoundDrawables(), etc.

So, when requestLayout() is called, it should be paired with a call to invalidate to ensure that the entire view is redrawn.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...