Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force a View to redraw itself

Tags:

java

android

I have created a custom View (let's call it MyView) which basically just draws some text on itself using the canvas. The text to be drawn is set using a global variable.

At some point during the program's execution, I want to change the global variable, and have the MyView redraw itself to update the text. I tried findViewById() and then invalidate(), but this does nothing. I suspect that since nothing within the MyView has changed, it thinks it has no reason to call onDraw(). Is there any way to force a View to redraw itself even if it thinks it doesn't need to?

like image 534
David John Welsh Avatar asked Aug 03 '11 13:08

David John Welsh


People also ask

Which method is used to redraw the view?

Invoking invalidate() on a View causes it to draw itself via the View. You should check this out: http://developer.android.com/guide/topics/ui/custom-components.html. A TextView internally invalidates itself when you invoke setText() and redraws itself with the new text set via the setText() call.

How do you refresh a layout?

Android provides a widget that implements the swipe-to-refresh design pattern, which allows the user to trigger an update with a vertical swipe. This is implemented by the SwipeRefreshLayout widget, which detects the vertical swipe, displays a distinctive progress bar, and triggers callback methods in your app.

What is invalidate in Android?

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() .


2 Answers

If I have a member variable inside the MyView that stores the text, and create a public setter for it, then just calling that method causes the MyView to redraw itself

Setting a variable inside the View will not invoke a draw on the View. In fact, neither does the view system know nor care about internal variables.

Invoking invalidate() on a View causes it to draw itself via the View. You should check this out: http://developer.android.com/guide/topics/ui/custom-components.html.

A TextView internally invalidates itself when you invoke setText() and redraws itself with the new text set via the setText() call. You should also do something similar.

like image 127
Vikram Bodicherla Avatar answered Sep 19 '22 14:09

Vikram Bodicherla


Okay so I figured it out. If I have a member variable inside the MyView that stores the text, and create a public setter for it, then just calling that method causes the MyView to redraw itself. Simple!

like image 26
David John Welsh Avatar answered Sep 21 '22 14:09

David John Welsh