Android:在 Fragment 里配置 RecyclerView(Fragment 通信)
如果只看定义,「在 Fragment 里配置 RecyclerView」很容易变成几个抽象名词。下面这段代码把它落成一个能运行的小程序,目标很明确:Fragment 创建后设置布局管理器和空适配器。
示例代码
顶部注释不是装饰,标的是每个关键函数/类为什么存在。读代码时可以从那里入手。
// 这段代码要解决的问题:Fragment 创建后设置布局管理器和空适配器
// 关键类/函数:
// - PostListFragment:列表页面 Fragment
// - onViewCreated():初始化视图
// - LinearLayoutManager:设置纵向布局
// 列表页面 Fragment
class PostListFragment : Fragment(R.layout.fragment_post_list) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val recycler = view.findViewById<RecyclerView>(R.id.recycler)
recycler.layoutManager = LinearLayoutManager(requireContext())
recycler.adapter = PostAdapter(emptyList())
}
}代码拆解
不必按顺序背 API,先盯住每个关键类/函数负责的那一段数据流。
PostListFragment:列表页面 FragmentonViewCreated():初始化视图LinearLayoutManager:设置纵向布局
边界情况
一次改太多行,出错后不知道是哪一步引入的;改一行,跑一次。
接下来动手
- 把示例删到只剩最核心的几行,确认它还能跑;再逐行加回被删掉的部分。
- 把
PostListFragment换成更小的版本,只保留当前示例需要的能力。
如果输出和预期不一致,先保留现场,再按注释里的职责逐段缩小范围。
评论 0
友善交流,让讨论变得更有价值。