Dynamically change AppWidget background with 9 patches

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

  • Created a FrameLayout for the widget of my application with ImageView as a background view.
  • Changed the ImageView image using the setImageViewResource() method.

Unfortunately, when it comes to 9-patch panels, this method does not work. Also, when the ImageView attribute android:src points to a 9-patch, it also does not work. Is there any way to change the background image of AppWidget using a 9 patch? Thanks in advance.

EDIT Sets the 9-patch as the source background in 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 does not stretch the image correctly, this code works fine. And the code for changing 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 like a 9-patch.

+4
source share
2 answers

This answer was diagnosed in the comments above ...

RemoteView does not allow access to View.setBackground() , so your workaround for using the android:src property for ImageView is good if the android:scaleType set to fitXY .

ImageView will not stretch the foreground image unless you report it.

+5
source

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

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

AFAIK, this is the most common approach to solving such problems. This is not ideal for two simple things that I could point out:

  • What will you do if your widget has n different "states" / "views"?

But while your files with 9 patches are also static resources, n is painful, but still theoretically manageable.

  • You need to keep track of changes in these concurrent files.

I would also like to find an easy way for this ...

This approach may not be for you also because it is basically a difficult path. Nevertheless, this is an option.


Offer No. 2

Have you tried to use 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 the background of the remote control RemoteView

+3
source

Source: https://habr.com/ru/post/1397760/


All Articles