如何在android中以编程方式更改api level 23下面的按钮的可绘制色调

问题描述 投票:7回答:3

我试图弄清楚如何以编程方式更改按钮的drawableLeft / drawableRight的颜色。我在我的xml中使用了drawable tint,如下所述,它的工作原理是> api level 23但是无法改变颜色<api​​ level 23

 <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="VIEW ALL"
                android:layout_centerInParent="true"
                android:background="#00000000"
                android:drawableLeft="@mipmap/ic_menu_black_36dp"
                android:layout_centerVertical="true"
                android:id="@+id/view_all"
                android:textColor="@color/bottom_color"
                android:drawableTint="@color/bottom_color"
                />
      Button  prev = (Button) findViewById(R.id.prev);

   Drawable[] drawables  =prev.getCompoundDrawables();
         drawables[0].setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
        prev.setCompoundDrawables(drawables[0],null,null,null);

方案:

 Drawable[] drawablesprev  =prev.getCompoundDrawables();

//for drawableleft drawable array index 0  

  drawablesprev[0].setColorFilter(getResources().getColor(R.color.assessment_bottom), PorterDuff.Mode.SRC_ATOP);

//for drawableright drawable array index 2  
drawablesprev[2].setColorFilter(getResources().getColor(R.color.assessment_bottom), PorterDuff.Mode.SRC_ATOP);


//for drawabletop drawable array index 1
  drawablesprev[1].setColorFilter(getResources().getColor(R.color.assessment_bottom), PorterDuff.Mode.SRC_ATOP);
android android-drawable android-button
3个回答
0
投票

你正在使用PorterDuff.Mode.MULTIPLY,所以你是倍增颜色。假设(你的drawable的名字)你的图标是黑色的 - #000000int它将是0。然后0 * GRAY(或任何其他颜色)将永远给你0,所以仍然是黑色...

尝试其他PorterDuff.Modes,例如PorterDuff.Mode.SRC_ATOPPorterDuff.Mode.SRC_IN

您当前的代码可能适用于白色版本的图标,应该使用MULTIPLY正确着色


3
投票

这是一种为TextView或Button drawable着色的快速方法:

  private void tintViewDrawable(TextView view) {
        Drawable[] drawables = view.getCompoundDrawables();
        for (Drawable drawable : drawables) {
            if (drawable != null) {
                drawable.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_ATOP);
            }
        }
    }

0
投票

对于kotlin来说,这对我有用

your_view.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)

或者如果您使用资源

your_view.setColorFilter(ContextCompat.getColor(this.baseContext, R.color.colorPrimary), PorterDuff.Mode.SRC_ATOP)
© www.soinside.com 2019 - 2024. All rights reserved.