使用"fill_parent"无法获得正确的布局

Naf*_*Kay 9 android android-layout

我正试图在Android中创建这个简单的布局.

在此输入图像描述

A应该换行以适应其内容并left|center_vertical对齐.

B应尽可能扩大,填补所有空白空间.

C应该是右对齐的,包装以填充其内容并且也是对齐的center_vertical.

这是我的布局:

<?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:orientation="horizontal"
        android:gravity="left|center_vertical">
    <!-- A -->
    <ImageView android:id="@+id/example_item_icon"
            android:layout_width="48px"
            android:layout_height="48px"/>
    <!-- B -->
    <LinearLayout android:orientation="vertical"
             android:layout_width="wrap_content"
             android:layout_height="fill_parent"
             android:gravity="left|center_vertical"
             android:padding="5px">

        <TextView android:id="@+id/example_item_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"/>

        <TextView android:id="@+id/example_item_level_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold|italic"
                android:lines="1"
                android:textSize="10px"/>
    </LinearLayout>
    <!-- C -->
    <TextView android:id="@+id/example_item_count_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:textSize="14px"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

在这种布局中,C被推离屏幕.如何使此布局有效?

Rom*_*Guy 19

fill_parent表示"与父级一样大",而不是"使用剩余的空白区域".而不是fill_parent,只需使用android:layout_width ="0dip"和android:layout_weight ="1".

  • @G_M父布局填充屏幕,因为它的高度和宽度设置为`match_parent`.这里的要点是组织A,B和C,以便它们在此父视图中正确填充空间.这正是重量的目的.通过给B赋予1的权重,并且A和C没有权重,您告诉父布局将其所有空间给予B,将A和C压缩到它们的最小宽度(包装它们的内容).因此,width属性对于B是无用的,因此我们将其设置为0dp以获得更好的性能.我希望这回答了你的问题. (5认同)