水平或垂直方向的Android LinearLayout项目填充剩余空间



我想知道是否可以在 LinearLayout 中有两个项目,一个包装其内容,另一个填充剩余的水平空间。我经常在 WPF (.NET) 中通过指定

HorizontalAlignment="Stretch".

例如:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="24dp"
    android:background="#0000FF"/>
<ImageView
    android:layout_width="match_parent"
    android:layout_height="24dp"
    android:background="#FF0000"/>

当我这样做时,第二个ImageView按预期填充整个水平空间。我试图同时设置wrap_content并使用重力,例如android:gravity="start"android:gravity="fill_horizontal"对于第二个,它不起作用。

注意:我可以通过指定权重属性来实现类似的东西。但这是根据百分比值提供的划分。这不是我想要的。

您可以使用权重属性本身执行此操作。尝试以下方法

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="24dp"
    android:background="#0000FF"/>
<ImageView
    android:layout_width="0dp"
    android:layout_height="24dp"
    android:layout_weight="1"
    android:background="#FF0000"/>

将其包含在水平线性布局中

您需要为此使用相对布局。此外,您要么需要为第一个图像视图指定宽度,要么它应该包含一个图像,否则,图像视图如何包装内容。

您可以像下面这样使用:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
    android:layout_alignParentLeft="true"
    android:id="@+id/imgFirst"
    android:layout_width="50dp"
    android:layout_height="24dp"
    android:background="#0000FF" />
<ImageView
    android:layout_width="match_parent"
    android:layout_height="24dp"
    android:layout_alignParentRight="@+id/imgFirst"
    android:layout_toRightOf="@+id/imgFirst"
    android:background="#FF0000" />
</RelativeLayout>

最新更新