Android – Margin/Padding Shrinks ImageView

androidandroid-layoutandroid-relativelayoutmarginpadding

I recently tried to position an imageview's x and y coordinates with no luck, it seems there is no way to do it in Gingerbread. I then decided to try out paddings and margins, but when I set them, it shrinks my imageview. I set a left padding of 250dp and image view became tiny. The layout_height and width are set to wrap_content. I'm not sure what's going on. Does anyone know why setting a padding/margin would shrink an imageview?

Best Answer

You're confusing margin and padding. Margin is the area outside of your view, while padding affects the content inside your margin.

Margins and Padding Example

If you set padding, then it is going to affect your available content area, and assuming you have a ScaleType set, it's going to shrink your image down to fit the available space.

Now, you say you've tried margins, but margins will do exactly what you're asking.

For example, if you wanted an ImageView placed 10dp from the top-left corner, you can do something like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <ImageView
        android:id="@+id/my_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:src="@drawable/my_image_id"
        />
</RelativeLayout>

Keep in mind that this places it 10dp with respect to the parent boundaries. If your parent layout also has padding, then that will affect your content placement.

Related Topic