Android RemoteViews, how to set ScaleType of an ImageView inside a widget?
Solution 1:
You can use this segment to set scale type for Image View programatically..
imgview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
Hope it helps...
Solution 2:
If you look at the source code of ImageView
, you can see the setScaleType
method lacks the @android.view.RemotableViewMethod
annotation, so it can't be called through the RemoteViews
interface.
There's a workaround for this limitation, but it's not pretty: define a different layout XML for each ScaleType you want, and choose between them just before you create the RemoteViews
. If your layout is complex, or you have more than one view to apply this workaround to, you might want to use RemoteViews.addView
to add the particular ImageView
layout inside the main layout.
I'm using this workaround (with addView
) for appwidgets in my app Showr. The problem with this method is that the stock launcher has a bug: if you change the scale type of an existing appwidget by creating a new RemoteViews
and calling addView
to add a different ImageView
layout to it, it doesn't always realise the layout has changed.
Solution 3:
Since the is no simple way to call setScaleType
on the remove view the work around I came up with was making three imageViews in my layout and then changing the visibility of the ones that don't have the scale type selected by the user:
// first I declared a map to associate preference values with imageView ids
private static final HashMap<Integer,Integer> widgetImageViewIds;
static {
widgetImageViewIds = new HashMap<Integer, Integer>();
widgetImageViewIds.put(MyAppPreferences.PREF_ALIGN_START, R.id.imageViewStart);
widgetImageViewIds.put(MyAppPreferences.PREF_ALIGN_CENTER, R.id.imageViewCenter);
widgetImageViewIds.put(MyAppPreferences.PREF_ALIGN_END, R.id.imageViewEnd);
}
...
// then when I update my widget show/hide the widgets based on the preference
for (HashMap.Entry<Integer, Integer> entry : widgetImageViewIds.entrySet()) {
Integer imageViewAlignment = entry.getKey();
Integer imageViewId = entry.getValue();
views.setViewVisibility(imageViewId, imageViewAlignment.intValue() != imageAlignmentPreferenceValue ? View.GONE : View.VISIBLE);
}