Search code examples
androidandroid-studiolayouttextviewbackground-color

Android get background color of parent view if no background color set


I have a a TextView for which I have not set a background color yet. I would like go the background color, but when I do ((ColorDrawable) mTextView.getBackground()).getColor() I obviously get a null pointer exception.

How would I traverse the view hierarchy of the TextView to find the most recent background color in the hierarchy that the TextView uses as background as a result.

And how would I determine the background color if no background color has been set in the hierarchy? And how would I determine that situation? How can I tell that no background has been set?

I basically have difficulty to determine the background color of a view when it has not been set explicitly.


Solution

  • I don't know how generally applicable this is but it does the trick for me:

    int getBackgroundColor(View view, int fallbackColor) {
        if (view.getBackground() instanceof ColorDrawable) {
            return ((ColorDrawable) view.getBackground()).getColor();
        } else {
            if (view.getParent() instanceof View)
                return getBackgroundColor((View) view.getParent(), fallbackColor);
            else
                return fallbackColor;
        }
    }
    
    

    It tries to cast the background as ColorDrawable and if that fails it tries again on its parent, recursively. If the parent is not a View, the specified fallback color is returned.

    Now for some Kotlin poetry:

    tailrec fun View.getBackgroundColor(): Int? =
        (background as? ColorDrawable)?.color
            ?: (parent as? View)?.getBackgroundColor()