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

时间:2017-06-15 09:23:20

标签: android android-studio layout textview background-color

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.

2 个答案:

答案 0 :(得分:2)

我不知道这在多大程度上适用,但是它对我有用:

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

它将尝试将背景投射为ColorDrawable,如果失败,它将递归地再次尝试对其父项进行尝试。如果父级不是View,则返回指定的后备颜色。

现在要读一些科特林的诗歌:

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

答案 1 :(得分:0)

Traverse in hierarchy depends upon what controls you have used.

now, to get color of layout, this can only be accomplished in API 11+ if your background is a solid color.

            int color = Color.TRANSPARENT;
            Drawable background = view.getBackground();
            if (background instanceof ColorDrawable)
            color = ((ColorDrawable) background).getColor();

once you get colorcode you can do operations based on that.