表达式“recyclerView”在edgar.yodgorbek.yangiliklar.sportactivities.BBCSportFragment.onCreateView(BBCSportFragment.kt:62)
处不能为null,通常是因为在onCreateView
方法中没有正确初始化recyclerView
,或者在布局文件中没有定义recyclerView
。
fragment_bbc_sport.xml
)中定义了RecyclerView
。onCreateView
方法中没有正确初始化RecyclerView
。在fragment_bbc_sport.xml
中添加RecyclerView
:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_bbc_sport, container, false)
val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
// 设置布局管理器
recyclerView.layoutManager = LinearLayoutManager(context)
// 设置适配器
val adapter = BBCSportAdapter()
recyclerView.adapter = adapter
return view
}
如果使用视图绑定,确保在build.gradle
文件中启用了视图绑定:
android {
...
viewBinding {
enabled = true
}
}
然后在Fragment
中使用视图绑定:
private var _binding: FragmentBbcSportBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentBbcSportBinding.inflate(inflater, container, false)
val view = binding.root
val recyclerView = binding.recyclerView
// 设置布局管理器
recyclerView.layoutManager = LinearLayoutManager(context)
// 设置适配器
val adapter = BBCSportAdapter()
recyclerView.adapter = adapter
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
通过以上步骤,应该可以解决recyclerView
为null的问题。
没有搜到相关的文章