Fragment
使用 Fragment 构建模块化用户界面。学习 Fragment 生命周期、Fragment 中的 ViewBinding、参数传递、返回栈管理以及 Fragment 与 Activity 之间的通信。
Fragment 是 CoddyKit 上的免费 Android Academy 课时。 这是第 6 节课,共 7 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Android Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Android Academy 课程共包含 7 节课。
什么是 Fragment?
Fragment 是存在于 Activity 内部的可复用界面模块。您可以把它看作一个拥有自己布局、生命周期和逻辑的子 Activity。
为什么要使用 Fragment?
- 在多个 Activity 之间复用界面
- 为手机和平板处理不同的布局
- 无需创建多个 Activity 即可构建多屏流程
- 与 Navigation Component 自然协作
Fragment 生命周期
Fragment 拥有自己的生命周期,并与 Activity 的生命周期同步运行。关键回调包括:
onAttach— Fragment 附加到 ActivityonCreate— Fragment 创建(此时还没有视图)onCreateView— 加载布局onViewCreated— 视图就绪,在此处设置界面onDestroyView— 视图销毁(清除视图引用)onDetach— Fragment 分离
创建 Fragment
创建一个继承自 Fragment 的类,并重写 onCreateView 来加载布局:
import androidx.fragment.app.Fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
}Fragment 中的 ViewBinding
在 Fragment 中使用 ViewBinding,但要在 onDestroyView 中释放绑定,以避免内存泄漏:
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.tvTitle.text = "Welcome!"
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null // prevent memory leak
}
}Fragment 布局 XML
像创建 Activity 布局一样创建 res/layout/fragment_home.xml。根视图会成为 Fragment 的视图:
<!-- res/layout/fragment_home.xml -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:text="Home" />
</LinearLayout>向 Activity 添加 Fragment
向 Activity 添加 Fragment 有两种方式:
- 静态(XML) — 使用
<fragment>标签在布局中声明。运行时固定不变。 - 动态(代码) — 使用
FragmentManager和事务。可以在运行时切换。
<!-- Static: in activity_main.xml -->
<fragment
android:id="@+id/homeFragment"
android:name="com.example.HomeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />动态 Fragment 事务
使用 supportFragmentManager 在运行时添加、替换或移除 Fragment:
// In Activity:
class MainActivity : AppCompatActivity(R.layout.activity_main) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.add(R.id.fragmentContainer, HomeFragment())
.commit()
}
}
fun showDetail(id: Int) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragmentContainer, DetailFragment.newInstance(id))
.addToBackStack(null) // allow back navigation
.commit()
}
}向 Fragment 传递参数
使用 Bundle 和伴生对象工厂模式传递数据。不要使用带参数的 Fragment 构造函数——配置发生变化后,Android 会使用无参构造函数重新创建 Fragment:
class DetailFragment : Fragment() {
companion object {
private const val ARG_ID = "item_id"
fun newInstance(itemId: Int): DetailFragment {
return DetailFragment().apply {
arguments = Bundle().apply {
putInt(ARG_ID, itemId)
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val itemId = requireArguments().getInt(ARG_ID)
// use itemId to load data
}
}Fragment → Activity 通信
在 Fragment 中定义一个接口,由 Activity 实现。Fragment 通过 onAttach 获取引用:
class ListFragment : Fragment() {
interface OnItemSelected {
fun onItemSelected(id: Int)
}
private var listener: OnItemSelected? = null
override fun onAttach(context: Context) {
super.onAttach(context)
listener = context as? OnItemSelected
}
private fun handleClick(id: Int) {
listener?.onItemSelected(id)
}
override fun onDetach() {
super.onDetach()
listener = null
}
}返回栈
在事务中调用 addToBackStack(null) 后,按下返回键会将 Fragment 从栈中弹出:
- 不使用
addToBackStack— 返回键会退出 Activity - 使用
addToBackStack— 返回键会回到上一个 Fragment - 使用
popBackStack()以编程方式返回
容器中的 Fragment
Activity 布局只需要一个容器视图——通常是带有 ID 的 FrameLayout。Fragment 会填充该容器:
<!-- activity_main.xml -->
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />快速检查
为什么绝不能向 Fragment 传递构造函数参数,而应通过伴生对象工厂使用 Bundle?
回顾:Fragment
Fragment 是现代 Android 界面的构建模块:
- 继承
Fragment,在onCreateView中加载布局 - 在
onViewCreated中设置界面 - 在
onDestroyView中释放 ViewBinding - 通过
Bundle和伴生对象工厂(newInstance)传递数据 - 使用
addToBackStack实现返回导航 - 通过接口与 Activity 通信
下一步:在运行时请求危险权限。
常见问题解答
「Fragment」课时是免费的吗?
是的 — 「Fragment」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Android Academy 课程的其余内容,请升级到 CoddyKit PRO。 Android Academy 课程共包含 7 节课。
「Fragment」这节课中我会学到什么?
使用 Fragment 构建模块化用户界面。学习 Fragment 生命周期、Fragment 中的 ViewBinding、参数传递、返回栈管理以及 Fragment 与 Activity 之间的通信。 你通过在浏览器中直接运行的动手代码来练习 Android Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Android Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Android Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 6 节课,共 7 节。
「Fragment」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Android Academy 课中编写并运行代码吗?
能。每节 Android Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。