【问题标题】:Get background color of a Layout获取布局的背景颜色
【发布时间】:2013-01-24 14:43:49
【问题描述】:

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

【问题讨论】:

标签: android background-color


【解决方案1】:

对于 kotlin 粉丝

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我只是要编辑我的答案并说具体可能会起作用!但是,我不确定为什么会有 API 11+ 限制? ColorDrawable 似乎从 API 1 开始可用,并且 view.getBackground() 也可用。
    • 没关系。我看到在 API 11 中添加了用于 ColorDrawable 的 .getColor
    • 您可以将Drawable 转换为Bitmap 并获得第一个像素。 int color = bitmap.getPixel(0, 0);
    • 我将这个((ColorDrawable) row.getBackground()).getColor() 用作(row.background as ColorDrawable).color,但我遇到了这个错误android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.ColorDrawable
    【解决方案3】:

    简单的方法:

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

    【讨论】:

      【解决方案4】:

      获取布局的背景颜色:

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

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

      【讨论】:

      • 是否有任何理由反对使用 ViewGroup(甚至是 View)而不是所有可能的子类来获取背景?
      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-14
        相关资源
        最近更新 更多