如何在Android中以编程方式更改小部件布局背景

时间:2011-06-01 12:50:34

标签: android layout background widget

以此小部件布局为例(我的整个小部件布局的一部分)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/widget_background_dark_4x2"
android:orientation="horizontal"
android:id="@+id/widget_main"
>

我希望能够根据用户选择更改使用的背景drawable。例如,使用远程视图,我可以通过执行以下操作来更新textview的颜色:

remoteView.setTextColor(R.id.text_view1, Color.WHITE);

然而,我发现我的线性布局背景很难相同。我试过这个:

remoteView.setBitmap(R.id.widget_main, "setBackgroundDrawable", ((BitmapDrawable) context.getResources().getDrawable(R.drawable.widget_background_dark_4x2)).getBitmap());

但是我收到以下错误:

06-01 22:46:36.305: WARN/AppWidgetHostView(244): android.widget.RemoteViews$ActionException: view: android.widget.LinearLayout doesn't have method: setBackgroundDrawable(android.graphics.Bitmap)

&LT;&LT;编辑&gt;&gt; 也尝试了这个:

Bitmap bitmap = ((BitmapDrawable)context.getResources().getDrawable(R.drawable.widget_background_light_4x2)).getBitmap();
remoteView.setBitmap(R.id.widget_main, "setBackgroundDrawable",bitmap );

但不幸的是得到以下错误:

06-01 23:11:26.039: WARN/AppWidgetHostView(244): updateAppWidget couldn't find any view, using error view 06-01 23:11:26.039: WARN/AppWidgetHostView(244): android.widget.RemoteViews$ActionException: view: android.widget.LinearLayout doesn't have method: setBackgroundDrawable(android.graphics.Bitmap)

2 个答案:

答案 0 :(得分:34)

你有没有尝试过:

remoteView.setInt(R.id.widget_main, "setBackgroundResource", R.drawable.widget_background_dark_4x2);

答案 1 :(得分:7)

好吧,我最终想出的唯一解决方案就是改变我在LinearLayout中显示背景图像的方式。如上所示,我使用android:background标签来显示图像。我最终做的是删除了这个,然后封装了我的整个小部件布局(在一个relativelayout里面的一个linearlayout里面。然后我在RelativeLayout中首先对一个ImageView进行了decalred然后让其余的小部件linearlayout位于顶部然后在我的代码中,我只是通过远程视图设置了imageview源,它就像是一种享受。

不是最优雅/最有效的编码方式,但它有效!