【问题标题】:Programmatically setting Button Background Drawable Color以编程方式设置按钮背景可绘制颜色
【发布时间】:2023-03-02 22:50:01
【问题描述】:

我事先创建了一个可绘制对象,它是一个矩形,但完全透明。现在我想将此drawable分配给代码中的Button,但还将此drawable的颜色从透明设置为某种特定颜色,例如橙色等。

我已经尝试使用其他一些帖子设置相同的 -

Drawable mDrawable = ContextCompat.getDrawable(this, R.drawable.square_transparent); 
    mDrawable.setColorFilter(
                    new PorterDuffColorFilter(
                            Color.Orange, Mode.SRC_IN)
                            );

但它不起作用。当activity渲染按钮时,它仍然只是透明的。

在将可绘制对象分配给按钮之前,我还尝试将 mDrawable.setAlpha 显式设置为 255(完全不透明),但即使这样也不起作用。

请建议,如果有人以其他方式进行此工作。

【问题讨论】:

    标签: android android-drawable porter-duff android-color


    【解决方案1】:

    使用Mode.SRC 而不是Mode.SRC_IN

    有关详细信息,请参阅PorterDuff modes

    【讨论】:

    • 这对@Gergely 没有任何帮助。这是我在应用程序中的实际代码 - Drawable mDrawable = ContextCompat.getDrawable(this, R.drawable.square_transparent); mDrawable.setColorFilter(new PorterDuffColorFilter(commonFuncCall.MapDigitToRColor(digitInput), Mode.SRC)); shape.setBackground(mDrawable);
    【解决方案2】:

    最后我使用两步解决方案得到了最终结果 -

    1. 我将可绘制对象从透明的变为没有不透明度的纯白色(似乎颜色过滤/着色,最适合白色)

    2. 我还使用下面的代码行来做到这一点 -

          Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.yourcustomshape, null);
      
          drawable = DrawableCompat.wrap(drawable);
      
          DrawableCompat.setTintList(drawable, ColorStateList.valueOf(Color.BLUE)); // Can be any color you need to color the shape
      

    【讨论】:

      【解决方案3】:

      使用两种方法可以设置背景颜色和边框

      这对于没有背景颜色

      public static GradientDrawable backgroundWithoutBorder(int color) {
      
              GradientDrawable gdDefault = new GradientDrawable();
              gdDefault.setColor(color);
              gdDefault.setCornerRadii(new float[] { radius, radius, 0, 0, 0, 0,
                      radius, radius });
              return gdDefault;
      
          }
      

      这用于与背景颜色

          public static GradientDrawable backgroundWithBorder(int bgcolor,
                  int brdcolor) {
      
              GradientDrawable gdDefault = new GradientDrawable();
              gdDefault.setColor(bgcolor);
              gdDefault.setStroke(2, brdcolor);
              gdDefault.setCornerRadii(new float[] { radius, radius, 0, 0, 0, 0,
                      radius, radius });
      
              return gdDefault;
      
          }
      

      【讨论】:

        猜你喜欢
        • 2021-05-20
        • 2021-10-18
        • 1970-01-01
        • 2014-06-24
        • 1970-01-01
        • 2013-11-07
        • 1970-01-01
        • 2021-07-04
        • 1970-01-01
        相关资源
        最近更新 更多