将小部件背景设置为以编程方式生成的渐变

Setting widget background to programmatically generated gradient

我正在努力让我的小部件看起来漂亮,但小部件反击了;(

我在将小部件布局背景设置为生成线性渐变时遇到问题。

目前,我已经找到了如何使用该渐变的自定义 "weigth" 颜色生成线性渐变:

public static PaintDrawable createLinearGradient(final int left, final int top, final int right, final int bottom, 
                                                 final int[] colors, final float[] positions)
{
    ShapeDrawable.ShaderFactory shaderFactory = new ShapeDrawable.ShaderFactory()
    {
        @Override
        public Shader resize(int width, int height)
        {
            LinearGradient lg = new LinearGradient(left, top, right, bottom, colors, positions, Shader.TileMode.REPEAT);
            return lg;
        }
    };

    PaintDrawable gradient = new PaintDrawable();
    gradient.setShape(new RectShape());
    gradient.setShaderFactory(shaderFactory);

    return gradient;
}

这是一种将小部件背景设置为可绘制文件夹中可绘制的方法:

int backgroundId =  getDrawableByName(context, "round_transparrent_background");
remoteViews.setInt(R.id.mainLayout, "setBackgroundResource", backgroundId);

我需要一种方法来编写如下命令:

Drawable background =  createLinearGradient(params ... );
remoteViews.setInt(R.id.mainLayout, "setBackgroundResource", background);

RemoteView 本质上仅限于某些功能。当您考虑到您传递给 RemoteViews 的任何信息都需要跨进程传输,并且并非所有 classes/data 类型都受支持时,这在一定程度上是有道理的。

无法将任意 Drawable 对象传递给 RemoteViews -- none 的方法支持它,并且 Drawable 通常不是 class 其数据可以跨进程编组。它适用于 drawable resources 的原因是资源 ID 只是一个整数,并且 Android 知道如何将它们膨胀成位图(对于 png)或它们各自的 Drawable 实现(对于使用 XML 声明的任何内容)。

在我看来,唯一可行的策略是使用 Canvas API 将渐变实际绘制到 Bitmap 中,并在 AppWidget 中使用 ImageView作为背景。然后你会调用 remoteViews.setImageViewBitmap() 来设置 ImageView.

的内容