Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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?

like image 663
LS_ Avatar asked Oct 12 '15 14:10

LS_


People also ask

How do I add a background to my layout?

in your parent layout element, e.g. linearlayout or whatever, simply add android:background="@drawable/background" This will set the background of your layout, assuming you have the image in a /drawable folder.

What is ScaleType in Android?

ScaleType is used for uniformly scaling the image bounds to the ImageView. Android ImageView provides various types of ScaleType for different configurations. CENTER.

What is scale type?

ScaleType options are used for scaling the bounds of an image to the bounds of the image view. ScaleType configuration properties for ImageView in Android are CENTER, CENTER_CROP, CENTER_INSIDE, FIT_CENTER, FIT_END, FIT_START, FIT_XY and MATRIX.


1 Answers

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>
like image 156
Simas Avatar answered Oct 19 '22 10:10

Simas