Sunday, May 24, 2015

How to stretch RelativeLayout background image in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#ffe0ffad"
    >
    <!--
        We cannot manage RelativeLayout background image scaling.
        So, to manage RelativeLayout background image, you
        can put the image inside an ImageView widget and put it
        center in layout. Then manage the image scaling by ImageView
        widget's attributes.
    -->
    <!--
        ImageView.ScaleType = CENTER
          Center the image in the view, but perform no scaling.

        ImageView.ScaleType = CENTER_CROP
          Scale the image uniformly (maintain the image's aspect ratio)
          so that both dimensions (width and height) of the image
          will be equal to or larger than the corresponding
          dimension of the view (minus padding).

        ImageView.ScaleType = CENTER_INSIDE
          Scale the image uniformly (maintain the image's aspect ratio)
          so that both dimensions (width and height) of the image will
          be equal to or less than the corresponding dimension
          of the view (minus padding).
    -->
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/animal"
        android:layout_centerInParent="true"
        android:scaleType="center"
        android:padding="0dp"
        android:layout_margin="0dp"
        />
</RelativeLayout>
More android examples