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

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

问题描述

我正在试验 Drawable 背景,到目前为止没有遇到任何问题.

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 可以在运行时更改它.甚至没有尝试 mutate() 可绘制对象,如下所述:可绘制突变

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?

推荐答案

是的!找到了方法!

不得不忘记 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天全站免登陆