嵌套视图强制它的父级大小为match_parent而不是wrap_content

时间:2015-09-15 22:47:26

标签: android android-layout

我想知道当父母有View时,是否有可能让layout_height="wrap_content"调整它的父高。在以下示例中:

<?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>

嵌套ImageView使RelativeLayout扩展它的高度以匹配它自己的父级。我想要实现的是RelativeLayout的高度等于内部TextViewImageView的高度应该在此处作为仅在文本后面的背景。如果没有Java代码技巧,这在纯XML中是否可行?

1 个答案:

答案 0 :(得分:3)

如果您使用RelativeLayout(就像您一样),您可以让View或ViewGroups布局通过id引用其他视图或ViewGroup。 在您的情况下,如果您为TextView android:ud="@+id/tvHello"分配了一个ID,那么您可以将ImageView的顶部和底部对齐到该TextView:

android:layout_alignTop="@+id/tvHello"
android:layout_alignBottom="@+id/tvHello"

为了完整起见,请点击您的布局:

<?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>

如您所见,我创建了ImageView 0dp的高度。我可以为wrap_content或甚至match_parent选择,但由于alignTop和alignBottom取代它,最好给视图一个固定的高度。这是由于性能。现在android不必测量ImageView的高度,然后决定使它与TextView的高度相同。

另一种方式(也许更好 - 取决于您希望图像如何缩放),是将drawable作为背景附加到RelativeLayout。就这样:

<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">

我希望这可以帮助你一点点而且它有用(这是我第一次回答stackoverflow)。

快乐的编码!

相关问题