改变渐变背景颜色在Android上运行时 [英] Changing gradient background colors on Android at runtime

查看:130
本文介绍了改变渐变背景颜色在Android上运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于改变渐变背景颜色在Android上运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆