带有 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,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,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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...