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.

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.