android - 带有 RemoteViews 的 setBackgroundResource 不适用于布局
问题描述
我正在尝试在我的应用小部件中设置我的布局的背景资源。我正在使用带有 RemoteViews 的 setBackground 资源,如下所示:
val views = RemoteViews(context.packageName, R.layout.first_money_widget)
views.setInt(R.id.widget_relativeLayout, "setBackgroundResource", R.drawable.widget_background_night)
这不会更改应用程序小部件的背景,但如果我在布局中更改它:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/widget_background_night"> // Here
...
</RelativeLayout>
它成功更改了后台资源。但是我需要它以编程方式进行更改,为什么我的代码没有更改后台资源?
我的 onRecieve 的完整代码:
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == "android.appwidget.action.APPWIDGET_UPDATE") {
Toast.makeText(context, "AppWidgetUpdate now", Toast.LENGTH_SHORT).show()
val views = RemoteViews(context.packageName, R.layout.widget_layout)
val appWidgetManager = AppWidgetManager.getInstance(context)
views.setInt(R.id.widget_relativeLayout, "setBackgroundResource", R.drawable.widget_background_night)
val cn = ComponentName(context, MyWidgetProvider::class.java)
appWidgetManager.updateAppWidget(cn, views)
}
更新:
我尝试将代码移至 onUpdate 方法,但它仍然没有设置 imageView 资源。只是为了测试,我试着做:
views.setViewVisibility(R.id.someViewInMyWidget, View.INVISIBLE)
代替:
views.setInt(R.id.widget_relativeLayout, "setBackgroundResource", R.drawable.widget_background_night)
令我惊讶的是,这并没有让人someViewInMyWidget
看不见。所以我怀疑它与专门设置imageViewResources有关。无论如何,我仍在寻找答案,任何帮助将不胜感激。
解决方案
几天后,我找到了答案。我只需要改变:
val appWidgetManager = AppWidgetManager.getInstance(context)
val cn = ComponentName(context, MyWidgetProvider::class.java)
appWidgetManager.updateAppWidget(cn, views)
至:
val widgetManager = AppWidgetManager.getInstance(context)
val appWidgetIds = widgetManager.getAppWidgetIds(ComponentName(context, MyWidgetProvider::class.java))
onUpdate(context, widgetManager, appWidgetIds)