首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RemoteView中的动态GradientDrawable

RemoteView中的动态GradientDrawable
EN

Stack Overflow用户
提问于 2014-01-13 23:28:31
回答 1查看 1.4K关注 0票数 3

为我的小部件设置动态背景时遇到了问题:

我的首选项返回用户选择的颜色,我想将其应用于小部件,但具有渐变效果。所以这就是我现在所处的位置:

我的widget.xml:

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/style_widget"
> ...

我的Service.java:

代码语言:javascript
复制
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);     

    remoteViews = new RemoteViews(this.getPackageName(), R.layout.widget);
    this.prefs = PreferenceManager.getDefaultSharedPreferences(this);       

    //this is where I get the color preference value, and create another with some transparency

    int color1 = prefs.getInt("background_color", 00000000);
    int color2 = Color.argb(22, Color.red(color1), Color.green(color1), Color.blue(color1));

    int colors[] = { color1, color2 };

            //Create the GradientDrawable:      
    GradientDrawable gradientDrawable = new GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM, colors);

如果我这样做了:

代码语言:javascript
复制
remoteViews.setInt(R.id.widget_layout, "setBackgroundColor", color1);

我更改了背景颜色,但由于gradientDrawable不是一个整数,如何通过remoteViews将其应用于我的背景?

EN

回答 1

Stack Overflow用户

发布于 2014-01-16 04:11:52

好吧,我在这里找到了答案:

Setting GradientDrawable through RemoteView

我创建了一个填充整个小部件的图像视图,然后使用我的gradientDrawable创建了一个位图,然后将该位图设置为图像视图:

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/style_widget"
android:padding="0dip" >

<ImageView
        android:id="@+id/bck_image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY"
    />

然后在我的服务中:

代码语言:javascript
复制
GradientDrawable gradientDrawable = new GradientDrawable(
                    GradientDrawable.Orientation.LEFT_RIGHT, colors);               

float dpi = getBaseContext().getResources().getDisplayMetrics().xdpi;
float dp = getBaseContext().getResources().getDisplayMetrics().density;

Bitmap bitmap = Bitmap.createBitmap(Math.round(288 * dp), Math.round(72 * dp), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap); 
gradientDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
gradientDrawable.setCornerRadius(5 * (dpi/160));
gradientDrawable.draw(canvas);
remoteViews.setImageViewBitmap(R.id.bck_image, bitmap);

(我对Android非常陌生,所以我不知道代码是否格式良好,但对我来说,它可以工作,以防它能帮助任何人。)

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21095025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档