Android:使用match_parent的布局应占用剩余空间或共享

时间:2015-09-22 17:25:31

标签: android android-layout layout fill-parent

我有一个水平线性布局,包含两个布局。我希望正确布局与内容(wrap_content)一样宽。 布局应填充剩余空间。

我试过" match_parent"在左侧布局(相对布局)和" wrap_content"在右侧布局(线性布局)上,但左侧布局采用全部空间。

如何解决这个问题,左侧布局只占用空间,而不是一切。就像让正确的布局占据空间一样。

EDIT :: 对不起,我想发布一张图片,但不能,这是代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:measureWithLargestChild="false">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff27"
    android:layout_gravity="bottom">
</RelativeLayout>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:layout_alignParentStart="true">

    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_alignParentStart="true" />
</LinearLayout>

左侧的相对布局占用所有空间(屏幕变为绿色)。 我希望相对布局采用LinearLayout保留的宽度,以便您可以在布局中看到该按钮。

2 个答案:

答案 0 :(得分:1)

Android按照它们在布局文件中出现的顺序布局视图。因此,在第二个视图有机会占用任何空间之前,您的第一个视图会填满所有可用空间。一种解决方法是使您的根布局成为RelativeLayout而不是LinearLayout,让您先放置右侧视图。另一种方法是保留根LinearLayout并使用layout_weight属性。在您的第一个视图中,请尝试android:layout_width="match_parent"android:layout_width="0dp"

,而不是android:layout_weight="1"

答案 1 :(得分:0)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
    android:orientation="horizontal">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="bottom"
        android:layout_weight="1"
        android:background="#00ff27"></RelativeLayout>

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

        <Button
            android:id="@+id/button"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="New Button" />
    </LinearLayout>
</LinearLayout>
相关问题