Question

There is no setBackground() method in the RemoteViews class, so I've used the following workaround:

  1. Created a FrameLayout for my app widget with an ImageView as the background view.
  2. Changed the ImageView image using setImageViewResource() method.

Unfortunately, when it comes to 9-patch drawables this method does not work. Also when an ImageView's android:src attribute points to 9-patch - it doesn't work too. Is there any way to change the AppWidget's background image programatically using a 9-patch drawable? Thanks in advance.

EDIT Settings the 9-patch as initial background in the XML:

<ImageView
    android:id="@+id/small_widget_layout_bg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background_lime" />

When I use android:src="@drawable/background_lime" it doesn't stretch the image properly, this code works fine. And the code to change the background from the AppWidgetProvider onUpdate method:

views.setImageViewResource(R.id.small_widget_layout_bg,
                    R.drawable.backgroung_lime);

This does not stretch the image as a 9-patch.

Was it helpful?

Solution

This answer was diagnosed in the above comments...

RemoteView doesn't allow access to View.setBackground(), so your workaround of using the android:src property of an ImageView is good, providing that the android:scaleType property is set to fitXY.

ImageView won't stretch it's foreground image unless you tell it to.

OTHER TIPS

Please ignore if u find this trivial or irrelevant, but canT you try (assuming you are dealing with widgets):

  • Declaring different layouts (xml)for your widget.
  • Change the remoteView's source (layout.id) instead of trying to make alterations to the selected layout.

AFAIK, this is the most common approach to solving such problems. This is not perfect for two simple things I could note myself:

  • What do you do if you have n different "states" / "views" in your widget?

But as long as your 9-patch files are also static resources, n is painful but still theoretically manageable.

  • It s tedious to keep track of the changes in these parallel files.

I'd also love to find an easy way for this one...

This approach may not be an option for you also because it is basically the hard way. But it s an option nonetheless.


Suggestion #2

Have you tried using the method?

public void setInt (int viewId, String methodName, int value)

remoteView.setInt(R.id.viewid, "setBackgroundResource", R.drawable.backgroung_lime);

From another question: Change remoteView ImageView background

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top