Sobes.tech
Junior — Middle

What distinguishes the invalidate and requestLayout methods in Android UI updates?

sobes.tech AI

Answer from AI

In Android, the methods invalidate() and requestLayout() are used to update the user interface, but they serve different purposes:

  • invalidate() — informs the system that the View needs to be redrawn. This triggers the onDraw() method, where the View's content is rendered. It is used when the visual appearance has changed, but the size and position have not.

  • requestLayout() — informs the system that the View needs to be measured and laid out again (calling onMeasure() and onLayout()). It is used when parameters affecting the size or position of the View have changed.

Example:

  • If you change the color or text in a View, call invalidate().
  • If you change the font size, which affects the size of the View, call requestLayout().

Thus, requestLayout() is more costly because it involves recalculating sizes and positions, whereas invalidate() only redraws.