24

What is the difference between Android's invalidate() and postInvalidate() methods? When does each one get called? Must the methods be called only in classes which extend View?

Pops
  • 30,199
  • 37
  • 136
  • 151
user918197
  • 1,129
  • 6
  • 17
  • 29

1 Answers1

43

If you want to re-draw your view from the UI thread you can call invalidate() method.

If you want to re-draw your view from a non-UI thread you can call postInvalidate() method.

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 UI thread another method is needed for when you are not in the UI thread and still want to notify the system that your View has been changed. The postInvalidate method notifies the system from a non-UI thread and the view gets redrawn in the next event loop on the UI thread as soon as possible. It is also shortly explained in the SDK documentation:

CLICK HERE

UPDATE:

There are some problems that arise when using postInvalidate from other threads (like not having the UI updated right-away), this will be more efficient:

runOnUiThread(new Runnable() {
    public void run() {
    myImageView.setImageBitmap(image);
    imageView.invalidate();
    }
});
Lii
  • 11,553
  • 8
  • 64
  • 88
Dharmendra
  • 33,296
  • 22
  • 86
  • 129
  • 3
    won't that be exactly what postInvalidate() does? – rupps Mar 29 '14 at 13:11
  • In android's example code: http://developer.android.com/training/custom-views/index.html, there is a PieChart.java which has property getters and setters inside. Most of the property setters calls invalidate();. Isn't PieChart.java not a UI thread and how come it can call invalidate from there? (there is a main activity java file which is the main thread). I would have expected a call to postinvalidate(); like how they did it under the onDraw method in PieChart.java. – Simon May 25 '14 at 14:29
  • @Simon I haven't looked at the code, but PieChart.java would still be working on the UI thread unless it extends Thread or specifies another thread to use in some other way. What's likely happening is the pie chart is drawn, then `postInvalidate()` is called within the pie chart's `onDraw` to draw the pie chart on a View in the UI thread. – Zach H Jul 08 '14 at 21:21