Android:在 Fragment 里配置 RecyclerView(Fragment 基础)
先不急着背概念。下面这个例子只做一件事: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())
}
}代码为什么这样写
PostListFragment:列表页面 FragmentonViewCreated():初始化视图LinearLayoutManager:设置纵向布局
结果不对时先看这里
复制代码时漏掉分号、缩进或导入,报错信息通常比代码本身更直接。
练习
- 先不看代码,写出你对「在 Fragment 里配置 RecyclerView」执行过程的预测,再运行对照。
- 改掉
PostListFragment的一行关键实现,观察报错信息,再恢复它。
别急着收藏。关掉页面,自己重写一遍,能独立跑通才算真的会。
评论 0
友善交流,让讨论变得更有价值。