Sobes.tech
Middle

Tell me about methods that redraw the View.

sobes.tech AI

Answer from AI

Methods:

  • invalidate(): Marks the View as "dirty", requiring redraw. Schedules onDraw() to be called in the future. Redraw occurs on the main thread. Used when external properties of the View (color, background, etc.) change.
  • postInvalidate(): Similar to invalidate(), but can be called from any thread, not just the main thread. Safe to use in background threads.
  • requestLayout(): Marks the View as "invalid", requiring recalculation of its size and position. Schedules onMeasure() and onLayout(), then onDraw(). Used when the size or position of the View changes (e.g., when adding/removing child elements in a ViewGroup).

Comparison of methods:

Method Calling thread Layout recalculation Redraw
invalidate() UI thread No Yes
postInvalidate() Any thread No Yes
requestLayout() UI thread Yes Yes (after layout)

Example of using invalidate():

// Change the color of the View and request redraw
myView.setBackgroundColor(Color.RED)
myView.invalidate()

Example of using requestLayout():

// Add a child element to LinearLayout and request layout recalculation and redraw
val newTextView = TextView(context)
linearLayout.addView(newTextView)
linearLayout.requestLayout()
Tell me about methods that redraw the View. — Android - sobes.tech