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

15
举个例子,这是一个小部件布局(我的整个小部件布局的一部分)。
<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"
>

我希望能够根据用户的选择更改使用的背景绘制。例如,使用远程视图,我可以通过执行以下操作来更新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)

<<编辑>> 也尝试了这个:

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 找不到任何视图,使用错误视图 06-01 23:11:26.039: WARN/AppWidgetHostView(244): android.widget.RemoteViews$ActionException: 视图:android.widget.LinearLayout没有方法:setBackgroundDrawable(android.graphics.Bitmap)
2个回答

48

你尝试过吗:

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

@khusrav widget_background_dark_4x2,请问您能告诉我确切的尺寸吗?我正在处理这个。 - RED.Skull
@RED.Skull 我没有这个确切的背景。你可以在这里查看应用程序小部件的尺寸指南:http://developer.android.com/guide/practices/ui_guidelines/widget_design.html - khusrav
@khusrav,谢谢。我使用FrameLayout实现了这个效果。感谢您的回复。 - RED.Skull
2
这应该是答案! - Nacho L.
这应该是答案! - Túlio Calazans

8
好的,我为此能想到的唯一解决方案是更改LinearLayout中显示背景图像的方式。 如您所见,我使用android:background标签来显示图像。 我最终做的是删除它,然后将整个小部件布局(位于relativelayout内的linearlayout内)进行封装。 然后,我首先在RelativeLayout中声明了ImageView,然后让其余的小部件LinearLayout位于其上方。 然后,在我的代码中,我只需通过远程视图设置imageview源,它就像魔法一样运行。
这不是最优雅/高效的编码方式,但它有效!

1
很方便,谢谢分享 :) - Fon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接