Middle
Tell about methods that cause View to redraw in Android.
sobes.tech AI
Answer from AI
invalidate() and requestLayout().
invalidate():
- Requests a redraw of the current View.
- Calls the
onDraw()method of the View. - Does not lead to recalculating the size and position of the View and its child elements.
- Used when only the appearance of the View has changed (e.g., color, text).
requestLayout():
- Requests a full measurement and layout cycle for the View.
- Calls the
onMeasure()andonLayout()methods of the View and its parent elements. - Leads to recalculating the size and position of the View and its child elements.
- Used when the size, position of the View, or its child elements have changed.
Example of using invalidate():
// Changing the background color of the View
view.setBackgroundColor(Color.RED)
view.invalidate() // Request the View to redraw with the new color
Example of using requestLayout():
// Changing the width of the View
val params = view.layoutParams
params.width = 200
view.layoutParams = params
view.requestLayout() // Request the View to re-measure and re-layout