What methods exist for redrawing a View in Android?
sobes.tech AI
Answer from AI
There are several main methods for managing View redraws in Android:
-
invalidate(): This method marks the current View and all its children as "dirty," requiring redraw. The system schedules a draw pass in the future (usually on the next frame). It is used when something affecting the appearance of the View (e.g., color, text) has changed. It can be called from any thread. -
postInvalidate(): Similar toinvalidate(), but intended to be called from background threads. It posts a message to the main UI thread to performinvalidate(). -
requestLayout(): This method indicates that the View needs to re-measure and re-layout itself. It triggers a measure and layout pass after the redraw. It is used when something affecting the size or position of the View has changed (e.g., adding/removing child elements, changing padding). It can only be called from the main UI thread.
If both the appearance and size/position of the View have changed, calling requestLayout() is often sufficient, as it usually calls invalidate() during the process. However, changing only the appearance directly requires only invalidate().
Example of using invalidate():
// Change the background color of the View on the main thread
myView.setBackgroundColor(Color.parseColor("#FF0000"));
myView.invalidate();
Example of using postInvalidate() from a background thread:
new Thread(new Runnable() {
@Override
public void run() {
// Change the text of the View in a background thread
myView.setText("New text");
myView.postInvalidate(); // Redraw via the main thread
}
}).start();
Example of using requestLayout():
// Change padding of the View and request a layout pass on the main thread
myView.setPadding(10, 10, 10, 10);
myView.requestLayout();
Understanding the View rendering lifecycle is important:
- Data changes (e.g., color, text, size).
- Call
invalidate()orrequestLayout(). - System schedules a redraw.
- Measure pass -
onMeasure()is called. - Layout pass -
onLayout()is called. - Draw pass -
onDraw()is called.
invalidate() triggers step 6, while requestLayout() triggers steps 4, 5, and 6.