3

I'm trying to set the background resource of my layout in my app widget. I'm using setBackground resource with RemoteViews like so:

val views = RemoteViews(context.packageName, R.layout.first_money_widget)
views.setInt(R.id.widget_relativeLayout, "setBackgroundResource", R.drawable.widget_background_night)

This doesn't change the app widget's background, but if I change it in my layout:

<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>

It changes the background resource successfully. But I need it to change programatically, why is my code not changing the background resource?

Full code of my 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)
    }

Update:

I tried moving the code over to the onUpdate method, and it still doesn't set the imageView resource. Just for testing, I tried doing:

views.setViewVisibility(R.id.someViewInMyWidget, View.INVISIBLE)

Instead of:

views.setInt(R.id.widget_relativeLayout, "setBackgroundResource", R.drawable.widget_background_night)

And to my surprise, this didn't make someViewInMyWidget go invisible. So I doubt its a problem to do with setting specifically imageViewResources. Anyway, I'm still looking for the answer and any help would be appreciated.

ADM
  • 20,406
  • 11
  • 52
  • 83
Amy
  • 1,114
  • 13
  • 35

1 Answers1

0

After a few days, I found the answer. I just needed to change:

val appWidgetManager = AppWidgetManager.getInstance(context)
val cn = ComponentName(context, MyWidgetProvider::class.java)
    appWidgetManager.updateAppWidget(cn, views)

to:

val widgetManager = AppWidgetManager.getInstance(context)
val appWidgetIds = widgetManager.getAppWidgetIds(ComponentName(context, MyWidgetProvider::class.java))
onUpdate(context, widgetManager, appWidgetIds)
Amy
  • 1,114
  • 13
  • 35