Reputation: 598
I am wondering if it is possible to make one View
adjust it's height to it's parent height when the parent has layout_height="wrap_content"
. In following example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/red"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/time"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"/>
</RelativeLayout>
the nested ImageView
makes RelativeLayout
expand it's height to match it's own parent. What I would like to achieve is that RelativeLayout
has height equal to the one of the inner TextView
and ImageView
should work here as a background spanning only behind the text. Is this possible in pure XML without Java code tricks?
Upvotes: 1
Views: 604
Reputation: 76
If you use a RelativeLayout
(as you do), you can have Views or ViewGroups layout referencing other Views or ViewGroups by id.
In your case, if you assign an id to your TextView android:ud="@+id/tvHello"
then you can align the top and bottom of your ImageView to that TextView:
android:layout_alignTop="@+id/tvHello"
android:layout_alignBottom="@+id/tvHello"
For completeness, here's your layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/red"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_alignTop="@+id/tvHello"
android:layout_alignBottom="@+id/tvHello"
android:src="@drawable/time"/>
<TextView
android:id="@+id/tvHello"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"/>
</RelativeLayout>
As you can see, I made the height of the ImageView 0dp
. I could've chosen for wrap_content
or maybe even match_parent
, but because the alignTop and alignBottom overrules it's, it is better to give the view a fixed height. This is due to performance. Now android doesn't have to measure the height of the ImageView, before it's to decide to make it the same height as your TextView after all.
One other way (and perhaps better - depending on how you want your images to scale), is to attach a drawable as background to your RelativeLayout. As such:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/time"
android:orientation="vertical">
I hope this helps you out a little bit and it's helpful (it is my first time answering on stackoverflow).
happy coding!
Upvotes: 3