FrameLayout(帧布局)

FrameLayout 是 Android 开发中的一种简单而轻量的 ViewGroup,用于将子 View 叠放在一个矩形区域内,通常用于显示单一内容或叠放多个 View(如图片覆盖文本)。它是 Android UI 框架中最简单的布局之一,适合特定场景,但功能有限。本教程基于 Android Studio(截至 2025 年 9 月,Koala 2024.1.1),详细讲解 FrameLayout 的概念、属性、使用方法、示例代码和最佳实践,适合初学者和需要深入理解的开发者。


1. FrameLayout 概念


2. FrameLayout 核心属性

以下是 FrameLayout 的常用 XML 属性(res/layout/ 中定义):

属性 适用对象 描述 示例
android:layout_gravity 子 View 控制子 View 在 FrameLayout 中的对齐方式(如 center, top, bottom android:layout_gravity="center"
android:foreground FrameLayout 设置前景图片(覆盖所有子 View) android:foreground="@drawable/overlay"
android:padding FrameLayout 内边距 android:padding="8dp"
android:layout_margin 子 View 外边距 android:layout_margin="4dp"
  • 注意
    • 子 View 默认堆叠在左上角,layout_gravity 可调整位置。
    • FrameLayout 不支持类似 LinearLayout 的 layout_weight 或 RelativeLayout 的相对定位。

3. 使用 FrameLayout

FrameLayout 可以通过 XML 或代码定义,以下展示两种方式。

3.1 XML 布局中使用

以下是一个图片覆盖文本的界面,使用 FrameLayout 叠放 ImageView 和 TextView。

  • 布局文件res/layout/activity_main.xml):

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
    
        <!-- ImageView -->
        <ImageView
            android:id="@+id/backgroundImage"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:src="@drawable/background"
            android:scaleType="centerCrop" />
    
        <!-- TextView (overlays ImageView) -->
        <TextView
            android:id="@+id/overlayText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/overlay_text"
            android:textSize="24sp"
            android:textColor="@android:color/white"
            android:background="#80000000" <!-- Semi-transparent background -->
            android:layout_gravity="center" />
    
        <!-- Button (overlays both) -->
        <Button
            android:id="@+id/actionButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/action"
            android:layout_gravity=
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值