【问题标题】:Wrap content is not working on Vertical line in Relative Layout?换行内容不适用于相对布局中的垂直线?
【发布时间】:2017-07-14 22:20:18
【问题描述】:

我正在使用带有背景颜色的 View 在相对布局中创建一条垂直线。包装内容不起作用,该行将整个视口作为高度。为什么会这样?附上我不起作用的代码

 <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="wrap_content"
android:background="#f5f5f5"
android:orientation="vertical"
tools:ignore="MissingPrefix">

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <View
        android:layout_width="2dp"
        android:layout_alignParentTop="true"
        android:layout_height="wrap_content"
        android:layout_marginLeft="21.5dp"
        android:background="#a9382b" />

    <TextView
        android:id="@+id/seeall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="20dp"
        android:textColor="#a9382b"
        android:textSize="11sp"
        tools:text="SEE ALL" />

</RelativeLayout>

</LinearLayout>

【问题讨论】:

    标签: android android-relativelayout


    【解决方案1】:

    在这种情况下将高度设置为wrap_content 根本行不通。

    一般来说,wrap_content 会给视图足够的大小以包含它“内部”的所有内容(无论是子视图还是只是 TextView 中的文本等),但您的 View 标记没有任何“内部”的东西来定义高度。在这种情况下,它将增长到填满所有可用空间。

    如果您希望您的 RelativeLayout 与其中的 TextView 一样高,并且您希望线条从上到下 大小,请为您的View标签:

        <View
            android:layout_width="2dp"
            android:layout_height="match_parent"
            android:layout_alignTop="@+id/seeall"
            android:layout_alignBottom="@+id/seeall"
            android:layout_marginLeft="21.5dp"
            android:background="#a9382b">
    

    【讨论】:

    • 其实,如果你这样做,你为layout_height设置什么值都没有关系; match_parentwrap_content0dp 都可以使用。 RelativeLayout 仅根据您在下面传递的约束(layout_alignFoo attrs)调整 View 的大小。