【我的安卓第一课】Activity 的伙伴 Fragment

1. 引言

在 Android 中,一个 Activity 就是一个页面。

以微信为例,使用 Android 的小伙伴如果注意观察的话,当我们进入朋友圈时,会有从右侧滑入新页面 的层次效果;当退出时,会有向右滑出页面显示出旧页面的效果,今日头条,QQ 等 App 也有这种效果。

但在我的联系人 等页面切换时,却没有这种效果,而是直接切换出对应页面 。前者就是平时所用的 Activity。而后者,就是本文要讲的组件------Fragment

|----------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------|
| fragment 切换 | activity 切换 |
| | |

在 Android 应用开发中,Fragment是一个至关重要的 UI 组件,它代表了 Activity 生命周期内的一个具有独立行为和用户界面的模块化片段 。自引入以来,Fragment 已成为构建灵活、可复用且适应性强的用户界面的核心工具,尤其在响应式设计和现代导航架构中扮演着不可或缺的角色。

2. Fragment 生命周期

由于 Fragment 依附于 Activity,故Fragment 生命周期直接受其宿主 Activity 状态的影响,但也能在 Activity 生命周期内管理自身的视图和数据。

  • 当一个Fragment所关联的Activity正处于运行状态(可见且栈顶)时,该Fragment也处于运行状态。
  • 当一个Activity进入暂停状态时(可见非栈顶),与它相关联的Fragment就会进入暂停状态。
  • 当一个Activity进入停止状态时(不可见非栈顶),与它相关联的Fragment就会进入停止状态,或者通过调用FragmentTransactionremove()replace()方法将FragmentActivity中移除,但在事务提交之前调用了addToBackStack()方法,这时的Fragment也会进入停止状态。进入停止状态的Fragment对用户来说是完全不可见的,有可能会被系统回收
  • Fragment总是依附于Activity而存在,因此Activity被销毁时,与它相关联的Fragment就会进入销毁状态 。或者通过调用FragmentTransactionremove()replace()方法将FragmentActivity中移除,但在事务提交之前并没有调用 addToBackStack() 方法,这时的Fragment也会进入销毁状态。

Activity 生命周期 单击

  1. onAttach():当FragmentActivity建立关联时调用。
  2. onCreate()
  3. onCreateView():为 Fragment创建视图(加载布局) 时调用
  4. onActivityCreate():确保与Fragment相关联的Activity创建完毕时调用。
  5. onStart()
  6. onResume()
  7. onPasue()
  8. onStop()
  9. onDestroyView():与Fragment关联的视图被移除时调用。
  10. onDestroy()
  11. onDetach():当FragmentActivity解除关联时调用。

3. Fragment 主要应用

如附录,Fragment 通常用作顶级导航 。其动态刷新页面或页面中的某一部分,而不需要为 Activity Stack 添加新元素。

4. 简单使用

4.1 创建Fragment

LeftFragment

java 复制代码
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.fragment.databinding.FragmentLeftBinding;

public class LeftFragment extends Fragment {
    private FragmentLeftBinding binding;

    public LeftFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentLeftBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }
}
xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Button"/>

</LinearLayout>

MainActivity

xml 复制代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/main">

    <fragment
        android:id="@+id/leftFrag"
        android:name="com.example.fragment.ui.frament.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
</LinearLayout>

这是最简单的 fragment 的使用,通过在 MainActivity 中添加 fragment 的 View。将其关联至 LeftFragment。随后在定义的 Java 代码中设置相应的 xml。

**Fragment 也是一个非常复杂的体系,这里只做 HelloWorld 级别的介绍 **

5. Activity与Frament通信

在开发时,经常需要在Activity与Fragment直接传递数据。由于 Fragment 是模块化 UI 组件,不能直接操作 Activity 的视图,因此需要通过安全、解耦的方式进行通信。

5.1 Activity -> Fragment

Activity -> Fragment 最简单、直接的通信方式:获得对应Fragment

java 复制代码
LeftFragment fragment = (LeftFragment) getSupportFragmentManager().findFragmentById(R.id.leftFrag);
if (fragment != null) {
    // 调用 LeftFragment 对应方法
}

5.2 Fragment -> Activity

Fragment -> Activity 最简单、直接的通信方式:获得对应Activity

java 复制代码
MainActivity mainActivity = (MainActivity) getActivity();
if (mainActivity != null) {
    // 调用 MainActivity 的方法
}

5.3 Fragment -> Fragment

Fragmeng 直接无法直接通信,通常使用 Activity 或 共享资源 转接。

6. 结论

综上所述,Android 应用中"从右滑入"的页面切换效果通常标志着层级式导航 的开始,传统上由启动新 Activity 实现,现代则常由 Navigation Component 驱动的 Fragment 层级跳转完成。而"直接出现"的效果,则是顶级同级导航 的标志,其背后的技术支柱正是 Fragment------它使得在单一 Activity 容器内高效、灵活地切换核心功能模块成为可能。理解 ActivityFragment 的分工与协作,以及它们在不同导航场景下的应用,是掌握现代 Android UI 架构的关键。

附录

特征维度 层级导航 顶级导航
导航目标 进入详情页、子功能 (如朋友圈、文章) 切换核心功能模块 (如"我的"、"联系人")
典型组件 Activity Fragment
技术实现 startActivity() (层级跳转) FragmentTransaction.replace() (同级跳转)
视觉反馈 从右滑入/ 向左滑出 淡入/ 淡出无动画
用户心智 "进入" -> "返回" (前进/后退栈) "切换到" (并列、平等的功能区)
底层结构 可能涉及多个 Activity 通常基于单个 Activity + 多个 Fragment
相关推荐
wstcl1 小时前
安卓app、微信小程序等访问多个api时等待提示调用与关闭问题
android·微信小程序·webapi
louisgeek2 小时前
Android Studio 打印中文乱码
android
眼镜会飞3 小时前
Flutter 3.x新版android端的build.gradle.kts文件配置arm64-v8a和armeabi-v7a等
android·前端·flutter
Nayuta3 小时前
字节跳动「移动 OS 部门」招聘安卓工程师,AI+OS 方向
android
00后程序员张4 小时前
iOS 应用上架常见问题与解决方案,多工具组合的实战经验
android·ios·小程序·https·uni-app·iphone·webview
恋猫de小郭4 小时前
Flutter 小技巧之有趣的 UI 骨架屏框架 skeletonizer
android·前端·flutter
Kapaseker5 小时前
Kotlin 老手怎么写代码?
android·kotlin
张风捷特烈6 小时前
鸿蒙纪·Flutter卷#03 | 从配置证书到打包发布
android·flutter·harmonyos
技术liul18 小时前
使用安卓平板,通过USB数据线(而不是Wi-Fi)来控制电脑(版本1)
android·stm32·电脑