Android 如果没有设置背景颜色,获取父视图的背景颜色

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

我有一个尚未设置背景颜色的 TextView。我想去背景颜色,但是当我做 ((ColorDrawable) mTextView.getBackground()).getColor() 时,我显然得到了一个空指针异常。

我将如何遍历 TextView 的视图层次结构以在层次结构中找到最新的 背景颜色,结果 TextView 将其用作背景。

并且如果层次结构中没有设置背景颜色,我将如何确定背景颜色?我将如何确定这种情况?如何判断没有设置背景?

当没有明确设置视图的背景颜色时,我基本上很难确定它。

遍历层次结构取决于您使用的控件

现在,要获得布局的颜色,如果您的背景是纯色,这只能在 API11+ 中完成。

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

一旦你得到colorcode你就可以根据它进行操作了。

我不知道这有多普遍适用,但它对我有用:

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,则返回指定的后备颜色。

现在来看一些 Kotlin 诗歌:

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