如何使线性布局和相对布局按百分比共享水平屏幕空间?

问题描述 投票:0回答:1

如何让线性布局和相对布局按百分比共享水平空间?

左边的

LinearLayout
需要占屏幕的百分比宽度,右边的
RelativeLayout
占掉剩下的就可以了。我把它作为两个
LinearLayout's
,它工作得很好,因为我可以使用
layout_weight
属性,将宽度定义为百分比,有点像这样:

android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight=".20"

但现在我需要右侧的布局为

RelativeLayout
,并且无法弄清楚如何保留所需的百分比,因为
RelativeLayout
没有
layout_weight
属性。我需要的看起来像:

android android-linearlayout android-relativelayout android-layout-weight
1个回答
0
投票

在包含在

android:layout_weight
中的视图中使用
RelativeLayout
是被禁止的,因为
RelativeLayout
不为底层视图提供该属性(注意以
layout_
开头的属性返回到父布局,即
RelativeLayout 
).

同理,在a

android:layout_weight
中使用
RelativeLayout
并不意味着它回到了
RelativeLayout
本身,而是回到了它的父布局已经是一个
LinearLayout

所以,这将正常工作,无论是

LinearLayout
还是
RelativeLayout

<?xml version="1.0" encoding="utf-8"?>
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:weightSum="1">
 
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.2"
        android:background="@color/teal_700" />
 
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.8"
        android:background="@color/teal_200">
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="This is some text in Relative Layout" />
 
    </RelativeLayout>
 
 
</LinearLayout>
© www.soinside.com 2019 - 2024. All rights reserved.