Get background color of a Layout

后端 未结 5 1156
醉梦人生
醉梦人生 2020-12-05 12:34

I want to find the background color of a Layout from my code. Is there any way to find it? something like linearLayout.getBackgroundColor()?

相关标签:
5条回答
  • 2020-12-05 13:02

    To get background color of a Layout:

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

    If It is RelativeLayout then just find its id and use there object instead of LinearLayout.

    0 讨论(0)
  • 2020-12-05 13:14

    This can only be accomplished in API 11+ if your background is a solid color.

    int color = Color.TRANSPARENT;
    Drawable background = view.getBackground();
    if (background instanceof ColorDrawable)
        color = ((ColorDrawable) background).getColor();
    
    0 讨论(0)
  • 2020-12-05 13:14

    ColorDrawable.getColor() will only work with API level above 11, so you can use this code to support it from API level 1. Use reflection below API level 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;
        }
    
    0 讨论(0)
  • 2020-12-05 13:14

    For kotlin fans

    fun View.getBackgroundColor() = (background as? ColorDrawable?)?.color ?: Color.TRANSPARENT
    
    0 讨论(0)
  • 2020-12-05 13:21

    Short and Simple way:

    int color = ((ColorDrawable)view.getBackground()).getColor();
    
    0 讨论(0)
提交回复
热议问题