我想从代码中找到布局的背景颜色。有没有办法找到它?类似于linearLayout.getBackgroundColor()
?
答案 0 :(得分:105)
如果您的背景是纯色,则只能在API 11+中完成。
int color = Color.TRANSPARENT;
Drawable background = view.getBackground();
if (background instanceof ColorDrawable)
color = ((ColorDrawable) background).getColor();
答案 1 :(得分:12)
获取布局的背景颜色:
LinearLayout lay = (LinearLayout) findViewById(R.id.lay1);
ColorDrawable viewColor = (ColorDrawable) lay.getBackground();
int colorId = viewColor.getColor();
如果它是RelativeLayout,那么只需找到它的id并使用那里的对象而不是LinearLayout。
答案 2 :(得分:10)
ColorDrawable.getColor()仅适用于11级以上的API级别,因此您可以使用此代码从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;
}
答案 3 :(得分:6)
简短的方式:
int color = ((ColorDrawable)view.getBackground()).getColor();
答案 4 :(得分:3)
科特林球迷
https://[UserName]:[Password]@vendorwebsite.com&format=XML