抱歉,如果格式或提供的信息是低于我的,我没有问过这里的问题之前。
我的Kotlin应用程序在使用. apply遍历某个片段内的某段代码时会在加载时崩溃。负责的片段代码如下所示:
class SitesFragment : Fragment() {
private var _binding: FragmentSitesBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
gatherManga()
val fragment = this
//binding.recyclerView.apply{
// layoutManager = GridLayoutManager(activity,3)
// adapter= CardAdapter(mangaList)
//}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_binding = FragmentSitesBinding.inflate(layoutInflater)
return binding.root
}
override fun onDestroyView(){
super.onDestroyView()
_binding = null
}
//Currently hardcoded for testing
private fun gatherManga(){
val manga1 = Manga(
R.drawable.slc,
"Chu-Gong",
"Solo-Leveling",
"Webnovel.com",
)
mangaList.add(manga1)
}
}
在当前代码下,应用运行良好,但一旦取消注解.apply行,它会成功构建,但会崩溃。知道我做错了什么吗?为什么会发生这种情况?代码旨在在片段内的回收器视图中显示mangaList。
1条答案
按热度按时间wfauudbj1#
onCreate方法在onCreateView之前调用,并且您尝试在回收程序初始化之前访问它
尝试将注解代码移动到onCreateView中
有关片段生命周期here的详细信息