Android自适应布局

顶部固定底部自适应

关键如下:

  • 使用LinearLayout作为父容器
  • 设置容器的orientation为vertical:垂直布局
  • 固定在容器顶部的子元素设置layout_height为wrap_content:使用内容高度作为元素的固定高度。
  • 底部自适应子元素设置layout_height为match_parent:改元素将会自适应,即抢占父元素剩余的空间。

代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:clipChildren="false"
    android:clipToPadding="false"
    android:focusable="false"
    android:orientation="vertical"
    >
    <!-- 顶部固定:设置layout_height为wrap_content,使其根据内容设置高度 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:focusable="false"
        android:background="@color/background_color"
        >
        ...
    </LinearLayout>

    <!-- 底部自适应:设置layout_height为match_parent,它将根据父容器进行自适应,即是抢占模式 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:focusable="false"
        android:background="@color/background_color"
        >
        ...
    </LinearLayout>
</LinearLayout>

顶部固定底部自适应

关键如下:

  • 使用LinearLayout作为父容器
  • 设置容器的orientation为horizontal:水平布局
  • 固定在容器左侧的子元素设置layout_width为wrap_content:使用内容宽度作为元素的固定宽度。
  • 右侧自适应子元素设置layout_width为match_parent:改元素将会自适应,即抢占父元素剩余的空间。

代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:clipChildren="false"
    android:clipToPadding="false"
    android:focusable="false"
    android:orientation="horizontal"
    >
    <!-- 左侧固定:设置layout_width为wrap_content,使其根据内容设置宽度 -->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:focusable="false"
        android:background="@color/background_color"
        >
        ...
    </LinearLayout>

    <!-- 右侧自适应:设置layout_width为match_parent,它将根据父容器进行自适应,即是抢占模式 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:focusable="false"
        android:background="@color/background_color"
        >
        ...
    </LinearLayout>
</LinearLayout>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容