64

What is the use of the postInvalidate() function in Android? I have been seeing this function in a lot of places. When I Googled, I came out with this much:

postInvalidate-- post an invalidate request on the UI-thread

I don't know what the phrase "invalidate request" there means. Can someone explain in detail what is happening here?

Pops
  • 30,199
  • 37
  • 136
  • 151
rogerstone
  • 7,541
  • 11
  • 53
  • 62

3 Answers3

133

Each class which is derived from the View class has the invalidate and the postInvalidate method. If invalidate gets called it tells the system that the current view has changed and it should be redrawn as soon as possible. As this method can only be called from your UIThread another method is needed for when you are not in the UIThread and still want to notify the system that your View has been changed. The postInvalidate method notifies the system from a non-UIThread and the View gets redrawn in the next eventloop on the UIThread as soon as possible. It is also briefly explained in the SDK documentation.

Just compare invalidate and postInvalidate.

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
MarioB.
  • 2,396
  • 2
  • 18
  • 15
  • 2
    I see the logics in your answer, but invalidate() also works in my non-UI class. Works just as fine as postInvalidate(). – Sebastian Aug 13 '12 at 13:21
  • 1
    Great answer. The Android docs doesn't explain that its meant to redraw the View. Cleared it right up :) – Andy Nov 09 '12 at 22:21
  • As @Sebastian mentioned, I also tried both `invalidate()` and `postInvalidate()` from a non-UI thread (using `Executors.newSingleThreadExecutor()`), but both of them works fine, at least there seems no problem. Anyone knows why? – starriet Dec 25 '20 at 15:45
24

By this method (postInvalidate()), you can invalidate a View from non-UI threads. To invalidate a View from UI-thread use invalidate() method.

The invalidation means, that the View.onDraw(Canvas) method will we called at some point in the future (not immediately) to redraw whole View (if the View is visible).

Android is redrawing Views automaticly, but sometimes is necessary to tell: "Hey, this View has been changed, redraw it as fast as possible."

More at:

http://developer.android.com/guide/topics/ui/how-android-draws.html

http://developer.android.com/reference/android/view/View.html#invalidate%28%29

branoholy
  • 963
  • 8
  • 13
4

In simple words, invalidate() method can be called from UI Thread and postInvalidate() can be called from non-UI Thread in order to tell android to update our Custom View after some changes are made to it.

Rahul Yadav
  • 143
  • 6