LS_
LS_

Reputation: 7129

How to set the ScaleType on a LinearLayout's background image

I have a linear layout like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:background="@drawable/bgapp" >

What I need now is the possibility to set the background image ScaleType value in order to fill the screen everytime, this because I'm going to download the image and then I'm going to set it as background but without ScaleType the images will not keep it's aspect ratio based on the screen densities.

What I found is this solution:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/bgapp"
    android:scaleType="centerCrop"
    android:gravity="bottom|left" />

But It doesn't work as expected.. Is there a way to set a LinearLayout scaleType property or do I need to change my layout?

Upvotes: 9

Views: 20906

Answers (1)

Simas
Simas

Reputation: 44118

View's background is stretched depending on the size of the View.

Image scaling is supported by ImageView, and to use it together with the LinearLayout you need an additional container, that will overlay the 2 children (e.g. a FrameLayout):

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/bgapp"
    android:scaleType="centerCrop"/>

  <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">
    ...
  </LinearLayout>
</FrameLayout>

Upvotes: 19

Related Questions