首页 > 技术文章 > 实现控件始终在窗口底部

karryK 2020-11-12 19:46 原文

Android控件始终在窗口底部

实现效果如下:
效果图

实现步骤:

1、使用 L i n e a r L a y o u t {LinearLayout} LinearLayout 布局

2、把想要在底部的那个控件的 a n d r o i d : l a y o u t _ w e i g h t {android:layout\_weight} android:layout_weight 设为 1,这个属性被设为非0值时,视图将会被拉伸,可以分配到额外的空间。(对于weight的用法参考这篇博客

a n d r o i d : g r a v i t y {android:gravity} android:gravity设为 b o t t o m {bottom} bottom,底部对齐

a n d r o i d : l a y o u t _ h e i g h t {android:layout\_height} android:layout_height 设为 0dp(设为match_parent、wrap_parent也行,这个不重要)

代码实现:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!-- 这是上面那个列表,下面那个控件才是保持在底部的-->
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"/>

    <!--整个LinearLayout里面的保持在窗口底部-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="bottom"
        android:orientation="horizontal">
        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:src="@drawable/cat2"
            android:id="@+id/addImageId"/>
        <TextView
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="名字"/>
        <EditText
            android:layout_width="40dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/addName"
            />
        <TextView
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="描述"/>
        <EditText
            android:layout_width="40dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/addDesc"
            />
        <Button
            android:layout_marginLeft="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加"
            android:id="@+id/addBtn" />
    </LinearLayout>
</LinearLayout>

推荐阅读