Change drawable start color and end color dynamically in android activity class

13,301

Solution 1

Yes, it is possible. You should use GradientDrawable to do this.

int colors[] = { 0xff255779, 0xffa6c0cd };

GradientDrawable gradientDrawable = new GradientDrawable(
        GradientDrawable.Orientation.TOP_BOTTOM, colors);

view.setBackgroundDrawable(gradientDrawable);

Change color code as per your requirement. Though I used Color.parseColor("color code"), its not working.

There are some option for Orientation like following.

GradientDrawable.Orientation.BOTTOM_TOP;
GradientDrawable.Orientation.LEFT_RIGHT;
GradientDrawable.Orientation.RIGHT_LEFT;

Solution 2

Chintan's solution is good enough if you don't mind to create the GradientDrawable again, but if you just want to change the colors without touching other attributes like padding etc, you can simply use setColors. In the following case it shows how to change startColor, centerColor, and endColor.

int color = screenshot.getPixel(x, y);
GradientDrawable drawable = (GradientDrawable)binding.layoutStation.getBackground();
int colors[] = { color, 0xffffffff, color };
drawable.setColors(colors);
Share:
13,301
nilkash
Author by

nilkash

Updated on June 04, 2022

Comments

  • nilkash
    nilkash almost 2 years

    Hi I am developing one android application in which I drawable resource to set backgroung for button. I want to change start and end color for that drawable programatically i.e. in activity class inside button click listener. My drawable looks like :

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
      android:shape="rectangle">
      <gradient android:startColor="#be584c" 
        android:endColor="#be584c"
        android:angle="270" />
      <corners android:radius="2dp" />
      <stroke android:width="1px"/>
    </shape>
    

    And I set it as background for button in xml file. android:background="@drawable/download_button"

    and i want to change start color and end color of this drawable in activity class how to do this. Is there any way to f=do this. Need help. Thank you.