我有一个TextView,我还没有设置背景色。我想去背景色,但当我这样做时 ((ColorDrawable) mTextView.getBackground()).getColor()
很明显,我得到一个空指针异常。
我如何遍历TextView的视图层次结构以找到最近的 背景色 在层次结构中,TextView作为背景使用。
而 如果在层次结构中没有设置背景色,我将如何确定背景色? 那这种情况我又该如何判断呢?如何判断没有设置背景色?
当一个视图的背景色没有明确设置时,我基本上很难确定它的背景色。
我不知道这有多普遍适用,但它对我来说是个好办法。
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的诗歌。
fun View.getBackgroundColor(): Int? =
(background as? ColorDrawable)?.color
?: (parent as? View)?.getBackgroundColor()
层次结构中的遍历取决于 你用了什么控制手段.
现在,要获得布局的颜色,这只能在API 11+中完成,如果你的背景是纯色的。
int color = Color.TRANSPARENT;
Drawable background = view.getBackground();
if (background instanceof ColorDrawable)
color = ((ColorDrawable) background).getColor();
一旦你得到 色码 你可以在此基础上进行操作。