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

Pel*_*lly 13 layout android 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"
>
Run Code Online (Sandbox Code Playgroud)

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

remoteView.setTextColor(R.id.text_view1, Color.WHITE);
Run Code Online (Sandbox Code Playgroud)

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

remoteView.setBitmap(R.id.widget_main, "setBackgroundDrawable", ((BitmapDrawable) context.getResources().getDrawable(R.drawable.widget_background_dark_4x2)).getBitmap());
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

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)
Run Code Online (Sandbox Code Playgroud)

<<编辑>>也试过这个:

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

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

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)

foo*_*faa 37

你试过了吗:

remoteView.setInt(R.id.widget_main, "setBackgroundResource", R.drawable.widget_background_dark_4x2);
Run Code Online (Sandbox Code Playgroud)

  • 这应该是答案! (2认同)

Pel*_*lly 7

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

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