How to stretch / scale background images in an Android linear layout?

Android Developer picture Android Developer · Oct 14, 2013 · Viewed 31.1k times · Source

I need some help making a background image stretch or scale both vertically and horizontally in a linear layout. Every time I try to set the background however, it doesn't stretch the image to fit the screen. I'm not concerned about keeping the aspect ratio either.

Here's what I've got in a test xml at the moment:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/title"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/background">
</LinearLayout>

Which looks like this in preview (and in the game):

enter image description here

If I change the layout_height to fill_parent I get a repeating background:

enter image description here I'm sure the solution is extremely basic, but for some reason I'm missing it. Any help would be appreciated

thanks

Answer

Jay Snayder picture Jay Snayder · Oct 14, 2013

Not sure what available background layout options are available for the background attribute of a layout, but you can always just put an ImageView as the first element in an outer FrameLayout with maximum width and height. Then anything else you put into the layout will be drawn on top of this image. And of course you can just load in a scaletype that you desire; such as fitXY perhaps for what you are trying to achieve.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView 
    android:id="@+id/background"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:contentDescription="@string/backgroundDescription"
    android:scaleType="centerCrop">
</ImageView>   
...