Android布局

LinearLayout
  • 如果只是指定一部分的控件layout_weight值,别的自动调节,UI效果会更好

  • 例如下面的效果就是:Button的宽度仍然按照wrap_content来计算,而EditText则会沾满屏幕所有的剩余空间。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <!-- 这里只指定了EditText的layout_weight,而让Button自动适应-->
    <EditText
    android:id="@+id/input_message"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:hint="在这里输入消息"
    />

    <Button
    android:id="@+id/send_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="发送"
    />
RelativeLayout
  • 基于父控件定位

    • layout_alignParentLeft 位于父控件左边
    • layout_alignParentRight 右边
    • layout_alignParentTop 上边
    • layout_alignParentBottom 下边
    • layout_centerInParent 正中间
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button 1"

    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    />
    <!--该按钮位于父容器左上角-->
  • 基于其他控件定位

    • layout_toLeftOf 左
    • layout_toRightOf 右
    • layout_above 上
    • layout_below 下
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button 1"

    android:layout_above="@+id/button3"
    android:layout_toLeftOf="@+id/button3"
    />
    <!-- button1位于button3的左上角-->
FrameLayout
  • 帧布局简单而且应用场景少,这种布局所有控件都会摆放在左上角
  • 默认会重叠放置,后面添加的控件会遮住前面的
percentlayout
  • 百分比布局是帧布局FrameLayout和相对布局RelativeLayout的扩展,提供了PercentFrameLayout 和 PercentRelativeLayout 两种新的布局方式。

  • 添加依赖:implementation 'androidx.percentlayout:percentlayout:1.0.0'

  • 百分比布局不是内置的布局,所以使用时要写完整的包路径

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.percentlayout.widget.PercentFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Button
    android:id="@+id/button1"
    android:text="Button 1"

    android:layout_gravity="left|top"
    app:layout_widthPercent="50%"
    app:layout_heightPercent="50%"
    />

    </androidx.percentlayout.widget.PercentFrameLayout>

    <!-- 实际上并不推荐使用 -->
0%