【问题标题】:Change drawable start color and end color dynamically in android activity class在 android 活动类中动态更改可绘制的开始颜色和结束颜色
【发布时间】:2013-07-15 09:07:16
【问题描述】:

您好,我正在开发一个 android 应用程序,在该应用程序中我可以绘制资源来设置按钮的背景。我想以编程方式更改该可绘制对象的开始和结束颜色,即在按钮单击侦听器内的活动类中。我的drawable看起来像:

<?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"

我想在活动类中更改此可绘制对象的开始颜色和结束颜色如何执行此操作。有没有办法 f= 这样做。需要帮忙。谢谢。

【问题讨论】:

    标签: android background drawable


    【解决方案1】:

    是的,这是可能的。您应该使用 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;
    

    【讨论】:

      【解决方案2】:

      如果您不介意再次创建 GradientDrawable,Chintan 的解决方案就足够了,但如果您只想更改颜色而不触及填充等其他属性,您可以简单地使用setColors。在以下情况下,它显示了如何更改 startColorcenterColorendColor

      int color = screenshot.getPixel(x, y);
      GradientDrawable drawable = (GradientDrawable)binding.layoutStation.getBackground();
      int colors[] = { color, 0xffffffff, color };
      drawable.setColors(colors);
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-14
          • 1970-01-01
          • 2022-11-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多