pqn pqn - 5 months ago 72
Android Question

How to make image fill RelativeLayout background without stretching

In my Android project, I am not quite sure how to make my background image fill the entirety of the

RelativeLayout
root element in XML, which is the size of the screen. I want to be sure that this works for all aspect ratios, so the image will clip vertically or horizontally as necessary. Does someone know how to do this easily? I've only seen questions regarding
ImageView
s and
Button
s, but not really generic
View
s.

My XML file currently:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/enclosing_rl"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background"
android:fitsSystemWindows="false">
<!-- Other elements -->
</RelativeLayout>

Answer

Other than turning your image into a nine patch I don't think this is possible. What you could do instead is add an ImageView as the first view in your RelativeLayout. Set layout_centerInParent to true and have the layout_width and layout_height set to match_parent. Then set scaleType to centerCrop. That will make sure the image fills the screen without any distortion, but depending on screen size/orientation either some of the top/bottom or left/right of the image may be cut off.

<ImageView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:scaleType="centerCrop"
            android:src="@drawable/background" />

Any other views in the RelativeLayout will appear on top of the ImageView, as long as it is the first view in the RelativeLayout (when you are in the xml).