android - 在 android Activity 类中动态更改可绘制的开始颜色和结束颜色

标签 android background drawable

您好,我正在开发一个 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/

相关文章:

ios - 未调用重大更改位置委托(delegate)方法

Android 按钮可绘制色调

android - 如何使用 xml 设置可绘制颜色的圆角半径?

android - 尝试在 Android 中使用 appcenter Distribute

java - 如何将用户锁定在主目录中

android - LocationClient.getLastLocation() 尽管已连接但返回 Null

android - 使用 ormlite 获取带有原始 sql 的游标

html - 在 css 中围绕文本制作一个完美的正方形 bg?

android - 无法将@drawable/转换为可绘制对象