Force a View to redraw itself

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.


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!


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());
    }
}

Tags:

Java

Android