改变渐变背景颜色在Android上运行时颜色、背景、Android

2023-09-12 08:53:11 作者:暮然回首n1还不走

我尝试用可绘制背景,有没有问题为止。

I'm experimenting with Drawable backgrounds and have had no problems so far.

我现在试图改变渐变背景色在运行时。

I'm now trying to change the gradient background color at runtime.

不幸的是,有没有API在运行时改变它,它似乎。甚至没有试图变异()的绘制,如下解释:可绘制突变

Unfortunately, there's no API to change it at runtime, it seems. Not even by trying to mutate() the drawable, as explained here: Drawable mutations

本示例XML看起来是这样的。它的工作原理,符合市场预期。

The sample XML looks like this. It works, as expected.

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#330000FF"
        android:endColor="#110000FF"
        android:angle="90"/>
</shape>

可悲的是,我想用各种颜色的列表,并且他们必须通过程序改变在运行时。

Sadly, I want a list with various colors, and they'd have to be programatically altered at runtime.

有另一种方式来创建此渐变背景在运行时?甚至不使用XML完全?

Is there another way to create this gradient background at runtime? Perhaps even not using XML altogether?

推荐答案

是的!找到了一种方法!

Yes! Found a way!

只好算了有关XML,但这里就是我如何做的:

Had to forget about XML, but here's how I did it:

在我getView()重载函数(ListAdapter)我刚:

On my getView() overloaded function (ListAdapter) I just had to:

    int h = v.getHeight();
    ShapeDrawable mDrawable = new ShapeDrawable(new RectShape());
    mDrawable.getPaint().setShader(new LinearGradient(0, 0, 0, h, Color.parseColor("#330000FF"), Color.parseColor("#110000FF"), Shader.TileMode.REPEAT));
    v.setBackgroundDrawable(mDrawable);

这给了我同样的结果作为XML的背景之上。现在,我可以通过编程设置背景颜色。

And that gave me the same result as the XML background above. Now I can programmatically set the background color.