NavigationDrawer内Fragment中RecyclerView为空的IllegalStateException问题
这个问题的核心是你搞混了Fragment的生命周期顺序,导致在视图还没加载完成时就去操作RecyclerView了。
错误原因拆解
Fragment的生命周期执行顺序是:onCreate() → onCreateView()(加载并返回布局) → onViewCreated()(视图已完全创建)
你现在在onCreate()里直接调用mainMenu,但此时onCreateView()还没执行,布局还没被inflate到Fragment中,通过kotlin synthetic生成的mainMenu自然就是null,触发了这个异常。
修复方案
把RecyclerView的初始化代码移到onViewCreated()方法里——这个回调就是专门用来处理视图初始化逻辑的,此时布局已经加载完成,控件引用也能正常获取:
class MainFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) : View? = inflater.inflate(R.layout.content_main, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 在这里初始化RecyclerView就不会出现null问题了 mainMenu.layoutManager = LinearLayoutManager(context) mainMenu.adapter = MyAdapter(itemList) { toast("${it.name} selected") } } }
额外注意点
- 再次确认
content_main.xml里RecyclerView的id确实是@+id/mainMenu,和你代码里引用的一致; - kotlin synthetic的控件引用依赖于当前Fragment的视图层级,只有当视图被正确加载并附加后,这些引用才会生效,所以永远不要在
onCreate()里直接操作控件。
内容的提问来源于stack exchange,提问作者hdx13_beatcode
相关产品推荐
相关产品推荐

