Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When it's necessary to execute invalidate() on a View?

My answer to this question was just accepted but I started to wonder when exactly one needs to invalidate() a View and when it is not necessary?

After a bit of thinking I came to realization that it should work more or less like this:

  • actual drawing of "everything" occurs after onResume()
  • in "free" time parts of the screen can be redrawn but only those that were invalidated (and everything underneath)

Therefore, it would seem, if I change something after onResume() (e.g. as a response to a button click, I should invalidate() the changed View).

However, from what scana in this question says, it must be more complex then that and it depends somethimes on what method one uses.

E.g. on whether one uses

lastClicked.setImageBitmap(); 

or

lastClicked.setImageResource(); 

So, when it's necessary to execute invalidate() on a View and how does it really work ?

like image 429
mjaskowski Avatar asked May 18 '12 06:05

mjaskowski


People also ask

What is invalidate in Kotlin?

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.

What does invalidate mean in programming?

In English, "invalidate" means to make something not valid. But "invalidate a view" in GUI programming is meant to make the view to be redrawn.

What is requestLayout?

If something about your view changes that will affect the size, then you should call requestLayout() . This will trigger onMeasure and onLayout not only for this view but all the way up the line for the parent views.


1 Answers

(Do consider accepting some answers)

Generally, invalidate() means 'redraw on screen' and results to a call of the view's onDraw() method. So if something changes and it needs to be reflected on screen, you need to call invalidate(). However, for built-in widgets you rarely, if ever, need to call it yourself. When you change the state of a widget, internal code will call invalidate() as necessary and your change will be reflected on screen. For example, if you call TextView.setText(), after doing a lot of internal processing (will the text fit on screen, does it need to be ellipsised, etc.), TextView will call invalidate() before setText() returns. Similarly for other widgets.

If you implement a custom view, you will need to call invalidate() whenever the backing model changes and you need to redraw your view. It can also be used to create simple animations, where you change state, then call invalidate(), change state again, etc.

like image 153
Nikolay Elenkov Avatar answered Sep 23 '22 21:09

Nikolay Elenkov