2

嗨,我正在开发一个 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"

我想在活动类中更改这个drawable的开始颜色和结束颜色如何做到这一点。有没有办法 f= 这样做。需要帮忙。谢谢你。

4

3 回答 3

10

对的,这是可能的。您应该使用GradientDrawable来执行此操作。

int colors[] = { 0xff255779, 0xffa6c0cd };

GradientDrawable gradientDrawable = new GradientDrawable(
        GradientDrawable.Orientation.TOP_BOTTOM, colors);

view.setBackgroundDrawable(gradientDrawable);

根据您的要求更改颜色代码。虽然我用过Color.parseColor("color code"),但它不起作用。

方向有一些选项,如下所示。

GradientDrawable.Orientation.BOTTOM_TOP;
GradientDrawable.Orientation.LEFT_RIGHT;
GradientDrawable.Orientation.RIGHT_LEFT;
于 2013-07-15T09:42:46.287 回答
1

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

int color = screenshot.getPixel(x, y);
GradientDrawable drawable = (GradientDrawable)binding.layoutStation.getBackground();
int colors[] = { color, 0xffffffff, color };
drawable.setColors(colors);
于 2018-08-09T01:40:33.000 回答
-1

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

于 2017-05-22T19:11:48.240 回答