0

I am using myLinearLayout.setBackgroundResource(R.drawable.my_drawable) to set the background of a LinearLayout. Is there any way to maintain the source image's aspect ratio (zooming to fit when necessary) when using this method instead of having the image stretch to fit the LinearLayout?

xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/background_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    ...

</LinearLayout>

java file:

backgroundLayout.setBackgroundResource(R.drawable.my_drawable);
Adam Johns
  • 35,397
  • 25
  • 123
  • 176

1 Answers1

2

When I have to set the background of a layout (lets name it Layout_A), I use a RelativeLayout as parent and inside it I put 2 items:

  • an ImageView with scaletype set to centercrop
  • Layout_A

The xml would be:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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:scaleType="centerCrop"
        android:src="@drawable/background"/>

    <Layout_A>

        ...

    </Layout_A>

</RelativeLayout>

And the code you would need to change the background would be:

ImageView ivBackground = (ImageView) rootView.findViewById(R.id.background);
ivBackground.setImageDrawable(getResources().getDrawable(R.drawable.my_drawable));

or:

ImageView ivBackground = (ImageView) rootView.findViewById(R.id.background);
ivBackground.setImageResource(R.drawable.my_drawable);
Fer
  • 1,956
  • 2
  • 28
  • 35
  • I used this answer, but with `FrameLayout` instead of `RelativeLayout` for the root element: http://stackoverflow.com/q/22875453/1438339. In practice there is probably no difference and either should be fine I would imagine. – Adam Johns Nov 01 '15 at 00:59