Vajira Lasantha Vajira Lasantha - 3 months ago 22
Android Question

Android widget WRAP_CONTENT not working [FIXED]

I have following widget in my app and it contains an

ImageView
with width and height set as
WRAP_CONTENT
. Root view is a
RelativeLayout
again with width and height set as
WRAP_CONTENT
.

enter image description here

My issue is why there are some padding (marked in black) on top and bottom of the widget? I want it to be perfectly square. Following is my widget layout.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_battery_2x2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000"
android:layout_margin="@dimen/widget_margin"
android:padding="@dimen/widget_padding" >

<ImageView
android:id="@+id/image_widget_arc_battery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff0000"
android:layout_alignParentLeft="true"/>
</RelativeLayout>


@dimen/widget_margin
and
@dimen/widget_padding
is zero.

ImageView
contains a dynamically generated Bitmap (width and height is 400).

Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);


This is my first widget app :) I'm kinda lost and can not figure out why this extra padding is there. Anybody has an idea?

Thanks for your help.

Answer

From App Widget Design Guidelines | Android Developers

When your widget is added, it will be stretched to occupy the minimum number of cells, horizontally and vertically, required to satisfy its minWidth and minHeight constraints.

Each device has a grid on its home screen that widgets are forcefully aligned with. You can even see on some devices that the aspect ratio of the grid cells change when rotating between portrait and landscape.

The docs at the link above have some advice for how to specify sizes for your widgets. Some of the information there might help you.

I would recommend that if you are only showing the ImageView, instead of using a RelativeLayout, use a FrameLayout with a gravity of center and a transparent background. That way the FrameLayout might get stretched but your ImageView should stay square.

Even better, you might not need a ViewGroup subclass at all. Just have the ImageView as your top level component and use a scale type of FIT_CENTER. Then your bitmap should square up inside the ImageView. (Oh, and don't specify a background color for the ImageView, just do the background color in the bitmap.)