Sobes.tech
Junior

How to trigger a redraw of a custom View in Android?

sobes.tech AI

Answer from AI

There are several ways to trigger a redraw (invalidate) of a custom View:

  1. invalidate():

    • Redraws the entire View.
    • Schedules a call to onDraw().
    • Used for simple redraws without specifying a particular area.
    // Inside your View or when interacting with it
    myCustomView.invalidate()
    
  2. invalidate(Rect dirty) or invalidate(int left, int top, int right, int bottom):

    • Redraws only the specified area of the View.
    • More efficient if only part of the View needs updating.
    // Redraw the area with coordinates (10, 20) to (100, 150)
    myCustomView.invalidate(10, 20, 100, 150)
    
    // Or using Rect
    val dirtyRect = Rect(10, 20, 100, 150)
    myCustomView.invalidate(dirtyRect)
    
  3. postInvalidate():

    • Safe to call from any thread, including background threads.
    • Posts an invalidate operation to the message queue for execution on the UI thread.
    // Called from a background thread
    Thread {
        // Perform long computations
        // ...
        myCustomView.postInvalidate()
    }.start()
    

Comparison of invalidate() and postInvalidate():

Method Thread execution Safe from background thread Purpose
invalidate() UI thread No Immediate redraw (as much as possible on the UI thread)
postInvalidate() UI thread Yes Deferred redraw by posting to the message queue

Relation to onDraw():

Calling any of the invalidate(...) methods schedules the execution of your View's onDraw() method. The Android system combines multiple invalidate requests into one when possible to optimize performance. onDraw() is called only when the system is ready to redraw.

When to use each method:

  • Use invalidate() when you are on the UI thread (e.g., in a click handler, after an animation) and the changes affect the entire View or you do not care about area optimization.
  • Use invalidate(Rect) or invalidate(int, int, int, int) for optimization if only part of the View changes and you are on the UI thread.
  • Use postInvalidate() when you need to call invalidate from a background thread.
  • Do not call invalidate() or postInvalidate() too frequently without necessity, as it can negatively impact performance. Call them only after data or state changes in the View that require a visual update.
How to trigger a redraw of a custom View in Android… - sobes.tech