获取布局的背景颜色

我想从我的代码中找到布局的背景颜色。有办法找到吗?比如 linearLayout.getBackgroundColor()

80738 次浏览

这只能在 API 11 + 中完成,如果你的背景是纯色的。

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

GetColor ()只能在 API 级别高于11的情况下工作,因此您可以使用此代码从 API 级别1支持它。使用 API 级别11以下的反射。

public static int getBackgroundColor(View view) {
Drawable drawable = view.getBackground();
if (drawable instanceof ColorDrawable) {
ColorDrawable colorDrawable = (ColorDrawable) drawable;
if (Build.VERSION.SDK_INT >= 11) {
return colorDrawable.getColor();
}
try {
Field field = colorDrawable.getClass().getDeclaredField("mState");
field.setAccessible(true);
Object object = field.get(colorDrawable);
field = object.getClass().getDeclaredField("mUseColor");
field.setAccessible(true);
return field.getInt(object);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return 0;
}

要获取布局的背景颜色:

LinearLayout lay = (LinearLayout) findViewById(R.id.lay1);
ColorDrawable viewColor = (ColorDrawable) lay.getBackground();
int colorId = viewColor.getColor();

如果它是 RelativeLayout,那么只需找到它的 id 并使用 there 对象而不是 LinearLayout。

简单明了的方法:

int color = ((ColorDrawable)view.getBackground()).getColor();

为了 Kotlin 的粉丝

fun View.getBackgroundColor() = (background as? ColorDrawable?)?.color ?: Color.TRANSPARENT

我认为有些情况下背景可能不是 ColorDrawable,所以我们需要在演员表前检查一下:

 if (view.background is ColorDrawable) {
val bgColor = (view.background as ColorDrawable).color
}