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

淺唱寂寞╮ 提交于 2019-12-05 07:06:24

问题


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.


回答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;



回答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);



回答3:


new GradientDrawable(GradientDrawable.Orientation.TL_BR, new int[]{0xFF141a24, 0xFF293f49, 0xFF72554c})



来源:https://stackoverflow.com/questions/17650488/change-drawable-start-color-and-end-color-dynamically-in-android-activity-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!