如何在LinearLayout中实现ListView占剩余高度及EditText与按钮3:1布局
实现方案详解
嘿,这需求很好解决,我给你整理了完整的实现代码和关键要点:
首先,你的根LinearLayout得先设置成match_parent的宽度,不然没法让子View占满屏幕宽度。核心是利用layout_weight属性来分配空间,这是LinearLayout实现弹性布局的关键:
- ListView的空间分配:因为是垂直布局,给ListView设置
layout_height="0dp"和layout_weight="1",它就会自动占据除了底部输入栏之外的所有剩余垂直空间,宽度设为match_parent就能占满屏幕。 - 底部输入栏的宽度比例:把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
相关产品推荐
相关产品推荐

