Force a View to redraw itself
Asked Answered
A

3

41

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?

Ardene answered 3/8, 2011 at 13:34 Comment(1)
I answered the same question here: https://mcmap.net/q/388106/-force-a-view-to-redraw-itselfCounterblow
D
60

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.

Domineering answered 12/8, 2011 at 14:12 Comment(1)
Sorry, you are right, I did indeed call invalidate(). I meant to say that calling invalidate() didn't work because the variable I was changing was external to the View (it was global). So I created an internal variable and changed that before invalidating.Ardene
A
2

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!

Ardene answered 12/8, 2011 at 11:35 Comment(0)
C
2

Example:

customView.set(...)
customView.requestLayout();
customView.invalidate();

Reference: android.widget.TextView#onConfigurationChanged

@Override
protected void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (!mLocalesChanged) {
        mTextPaint.setTextLocales(LocaleList.getDefault());
        if (mLayout != null) {
            nullLayouts();
            requestLayout();
            invalidate();
        }
    }
    if (mFontWeightAdjustment != newConfig.fontWeightAdjustment) {
        mFontWeightAdjustment = newConfig.fontWeightAdjustment;
        setTypeface(getTypeface());
    }
}
Caudal answered 8/9, 2022 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.