问题描述
您好,我正在开发一个Android应用程序,在其中可绘制资源以设置按钮的背景.我想以编程方式更改该可绘制对象的开始和结束颜色,即在按钮单击侦听器内的活动类中.我的可绘制对象看起来像:
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>
然后将其设置为xml文件中按钮的背景. android:background="@drawable/download_button"
And I set it as background for button in xml file. android:background="@drawable/download_button"
,我想在活动类中更改此drawable的开始颜色和结束颜色.有什么办法可以做到这一点.需要帮忙.谢谢.
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.
推荐答案
是的,有可能.您应该使用 GradientDrawable 来做到这一点.
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);
根据您的要求更改颜色代码.尽管我使用了Color.parseColor("color code")
,但是它不起作用.
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;
这篇关于在android活动类中动态更改可绘制的开始颜色和结束颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!