【问题标题】:Is android:layout_weight only for LinearLayout or you can use it in RelativeLayout too?android:layout_weight 仅适用于 LinearLayout 还是您也可以在 RelativeLayout 中使用它?
【发布时间】:2020-03-18 21:53:19
【问题描述】:

如果 android:layout_weight 仅适用于 LinearLayout 为什么?

【问题讨论】:

    标签: android android-linearlayout android-relativelayout android-layout-weight


    【解决方案1】:

    阅读Layout Weight

    此属性根据视图应在屏幕上占据多少空间为视图分配一个“重要性”值。较大的权重值允许它扩展以填充父视图中的任何剩余空间。子视图可以指定一个权重值,然后视图组中的任何剩余空间按照其声明权重的比例分配给子视图。默认权重为零。

    相对布局显示其视图彼此之间的相对关系,因此顺序并不那么重要。

    【讨论】:

    • 非常感谢您的回答,那么如果我想插入一个 EditText 怎么办(它会根据屏幕的大小而增加,例如当我们写一封电子邮件时,它会增加(方框)所以你的意思是只要有EditText就应该放在LinearLayout中?所以我们可以应用layout_weight?我们不能在RelativeLayout中使用EditText?
    【解决方案2】:

    android:layout_weight 是 LinearLayout 的属性,它会将这个属性继承给它的孩子,所以在你的情况下,如果你的孩子是 RelativeLayout 那么我们可以使用 android:layout_weight 和 RelativeLayout。

    见下例

    <androidx.appcompat.widget.LinearLayoutCompat
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_centerInParent="true">
    
                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"/>
    
                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"/>
    
            </androidx.appcompat.widget.LinearLayoutCompat>
    

    就是这样

    【讨论】:

    • 非常感谢您的回答,那么如果我想在 EditText 插入(它会根据屏幕的大小而增加,例如当我们写一封电子邮件时,它会增加(框)所以你的意思是只要有EditText就应该放在LinearLayout中?所以我们可以应用layout_weight?我们不能在RelativeLayout中使用EditText?
    【解决方案3】:

    RelativeLayout 没有权重属性,但 ConstraintLayout 具有权重属性,如 LinearLayout。

    layout_constraintHorizontal_weight layout_constraintVertical_weight

    【讨论】:

    • 非常感谢您的回答,那么如果我想在 EditText 插入(它会根据屏幕的大小而增加,例如当我们写一封电子邮件时,它会增加(框)所以你的意思是只要有EditText就应该放在LinearLayout中?所以我们可以应用layout_weight?我们不能在RelativeLayout中使用EditText?
    猜你喜欢
    • 2016-10-15
    • 2019-11-25
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多