How to change Drawable color dynamically for buttons
Asked Answered
M

1

5

I have drawable xml up.xml as in the following code

 <?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>

and I have this drawable attached to a button as follows

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

I'm trying to change the color of the solid android:color="@color/green" in the up.xml file dynamically in my code. I tried the following, but it didn't work.

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

I get the following error java.lang.ClassCastException: android.graphics.drawable.LayerDrawable cannot be cast to android.graphics.drawable.GradientDrawable

Can anyone help? Thank you.

Manysided answered 13/6, 2017 at 1:42 Comment(1)
#22002041Superinduce
M
9

try this my friend

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

Kotlin code

    val myIcon =ContextCompat.getDrawable(this@LoginActivity,R.drawable.button)
    val filter: ColorFilter = LightingColorFilter(Color.BLACK, Color.BLACK)
    myIcon.colorFilter = filter
Melina answered 13/6, 2017 at 4:31 Comment(1)
@Parthan_akon happy to help youMelina

© 2022 - 2024 — McMap. All rights reserved.