获取布局的背景颜色

Sru*_*mha 55 android background-color

我想从我的代码中找到布局的背景颜色.有没有办法找到它?类似的东西linearLayout.getBackgroundColor()

Ric*_*ich 116

如果您的背景是纯色,则只能在API 11+中完成.

int color = Color.TRANSPARENT;
Drawable background = view.getBackground();
if (background instanceof ColorDrawable)
    color = ((ColorDrawable) background).getColor();
Run Code Online (Sandbox Code Playgroud)


小智 12

要获取布局的背景颜色:

LinearLayout lay = (LinearLayout) findViewById(R.id.lay1);
ColorDrawable viewColor = (ColorDrawable) lay.getBackground();
int colorId = viewColor.getColor();
Run Code Online (Sandbox Code Playgroud)

如果它是RelativeLayout然后只是找到它的id并使用那里的对象而不是LinearLayout.


Akh*_*Dad 11

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;
    }
Run Code Online (Sandbox Code Playgroud)


Dom*_*icz 7

对于 kotlin 粉丝

fun View.getBackgroundColor() = (background as? ColorDrawable?)?.color ?: Color.TRANSPARENT
Run Code Online (Sandbox Code Playgroud)


Aas*_*ish 6

简单方法:

int color = ((ColorDrawable)view.getBackground()).getColor();
Run Code Online (Sandbox Code Playgroud)