您好,我正在开发一个 Android 应用程序,我在其中可以绘制资源来为按钮设置背景。我想以编程方式更改该可绘制对象的开始和结束颜色,即在按钮单击监听器内的 Activity 类中。我的可绘制对象看起来像:
<?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"
我想在 Activity 类中更改此可绘制对象的开始颜色和结束颜色如何执行此操作。有什么办法可以做到这一点。需要帮忙。谢谢。
最佳答案
是的,这是可能的。您应该使用 GradientDrawable 来执行此操作。
int colors[] = { 0xff255779, 0xffa6c0cd };
GradientDrawable gradientDrawable = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM, colors);
view.setBackgroundDrawable(gradientDrawable);
根据您的要求更改颜色代码。虽然我使用了 Color.parseColor("color code")
,但它不起作用。
Orientation 有一些选项,如下所示。
GradientDrawable.Orientation.BOTTOM_TOP;
GradientDrawable.Orientation.LEFT_RIGHT;
GradientDrawable.Orientation.RIGHT_LEFT;
关于android - 在 android Activity 类中动态更改可绘制的开始颜色和结束颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17650488/