简体   繁体   中英

Set background with gravity without resizing the container View in Android

How can I add a background to a view, without resizing its size, only showing the part of the image that fits the previous space?

Example:

I have the following initial layout:

在此处输入图片说明

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#8900"
    android:orientation="vertical"
    tools:context="com.tappx.myapplication.MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:background="#0f0"
            android:gravity="center"
            android:text="HELLO" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:background="#f0f"
            android:gravity="center"
            android:text="HELLO" />


    </LinearLayout>


</LinearLayout>

And I want to apply the following image as gradient to the white background:

在此处输入图片说明

To achieve this (please note the gradient is filling the horizontal and has bottom gravity):

TARGET: 在此处输入图片说明

My problem is that setting the gradient as android:background expands the container view size to this (losing the red bottom part)

在此处输入图片说明

Also tried making a xml bitmap with no results:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <bitmap
            android:gravity="bottom"
            android:src="@drawable/gradient" />
    </item>
</layer-list>

How can I achieve it?

The image you are using is very long, and your container is set to wrap content and so it is expanding to accommodate the image.

Since you are already using fixed heights on the inner elements, you can simply set a fixed height for the container (200dp) and it'll work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM