Reputation: 7536
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.
Upvotes: 2
Views: 14148
Reputation: 7238
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);
Upvotes: 2
Reputation: 298
new GradientDrawable(GradientDrawable.Orientation.TL_BR, new int[]{0xFF141a24, 0xFF293f49, 0xFF72554c})
Upvotes: -1
Reputation: 26034
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;
Upvotes: 10