【问题标题】:How to change Drawable color dynamically for buttons如何动态更改按钮的可绘制颜色
【发布时间】:2017-11-14 14:50:13
【问题描述】:

我有可绘制的 xml up.xml,如下代码所示

 <?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <rotate
        android:fromDegrees="45"
        android:toDegrees="45"
        android:pivotX="-40%"
        android:pivotY="87%" >
        <shape
            android:shape="rectangle" >

            <solid
                android:color="@color/green" />
        </shape>
    </rotate>
</item>
</layer-list>

我将这个drawable附加到一个按钮上,如下所示

   <Button android:id="@+id/bill_amount_up"
   android:layout_width="30dp"
   android:layout_height="30dp"
   android:background="@drawable/up"
     />

我正在尝试在我的代码中动态更改 up.xml 文件中的纯色 android:color="@color/green" 的颜色。我尝试了以下方法,但没有成功。

 ((GradientDrawable)billAmountUp.getBackground()).setColor(color);

我收到以下错误 java.lang.ClassCastException: android.graphics.drawable.LayerDrawable 不能转换为 android.graphics.drawable.GradientDrawable

有人可以帮忙吗?谢谢。

【问题讨论】:

标签: android android-layout drawable android-drawable android-color


【解决方案1】:

我的朋友试试这个

Drawable myIcon = getResources().getDrawable( R.drawable.button ); 
ColorFilter filter = new LightingColorFilter( Color.BLACK, Color.BLACK);
myIcon.setColorFilter(filter);

Kotlin 代码

    val myIcon =ContextCompat.getDrawable(this@LoginActivity,R.drawable.button)
    val filter: ColorFilter = LightingColorFilter(Color.BLACK, Color.BLACK)
    myIcon.colorFilter = filter

【讨论】:

  • @Parthan_akon 很乐意为您提供帮助