You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LinearLayout中实现ListView占剩余高度及EditText与按钮3:1布局

实现方案详解

嘿,这需求很好解决,我给你整理了完整的实现代码和关键要点:

首先,你的根LinearLayout得先设置成match_parent的宽度,不然没法让子View占满屏幕宽度。核心是利用layout_weight属性来分配空间,这是LinearLayout实现弹性布局的关键:

  1. ListView的空间分配:因为是垂直布局,给ListView设置layout_height="0dp"和layout_weight="1",它就会自动占据除了底部输入栏之外的所有剩余垂直空间,宽度设为match_parent就能占满屏幕。
  2. 底部输入栏的宽度比例:把EditText和按钮放在一个水平方向的LinearLayout里,通过layout_weight分配宽度——EditText设为3,按钮设为1,同时它们的宽度都设为0dp,这样就能严格按照3:1的比例分配宽度。

完整的布局代码如下:

<?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="vertical">

    <!-- 占据剩余空间的ListView -->
    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <!-- 底部输入栏:EditText与按钮宽度3:1 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="8dp">

        <EditText
            android:id="@+id/edit_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:hint="输入内容..." />

        <Button
            android:id="@+id/send_btn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="发送" />
    </LinearLayout>

</LinearLayout>

再补两个关键属性的小说明:

  • layout_weight:在LinearLayout中,当子View的对应方向尺寸设为0dp时,weight值决定了它占据剩余空间的比例——垂直布局时影响高度,水平布局时影响宽度。
  • 根LinearLayout的layout_width="match_parent":确保整个布局占满屏幕宽度,不然子View的match_parent也没法生效。

内容的提问来源于stack exchange,提问作者Hatay Berkay Işıkoğlu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:20:38