首页 > 解决方案 > 嵌套的 LinearLayout 拉伸

问题描述

考虑这种布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/red"
                android:background="@color/Red"
                android:gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Red" />

        </LinearLayout>
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

一直水平拉伸到屏幕边缘,但高度受TextView字符串“Red”限制,位于屏幕顶部。为什么呢?为什么TextView只有一维拉伸?

当我切换LinearLayouts 的方向时,效果是相反的:TextView从上到下拉伸,但它的宽度受字符串“Red”的限制,并与屏幕左侧对齐。

标签: androidandroid-linearlayout

解决方案


android:layout_weight="1"从中取出TextView并检查。

注意:如果您正在使用,ConstraintLayout则无需服用LinearLayout. 一切都可以由ConstraintLayout. 您只需要设置适当的视图约束。


推荐阅读