Подтвердить что ты не робот

Получить цвет фона макета

Я хочу найти цвет фона макета из моего кода. Есть ли способ найти его? что-то вроде linearLayout.getBackgroundColor()?

4b9b3361

Ответ 1

Это может быть выполнено только в API 11+, если ваш фон является сплошным цветом.

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

Ответ 2

ColorDrawable.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;
    }

Ответ 3

Чтобы получить цвет фона макета:

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

Если это RelativeLayout, просто найдите его id и используйте там объект вместо LinearLayout.

Ответ 4

Самый простой способ сделать это:

view.getSolidColor();