kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
at space.rodionov.financialsobriety.ui.transaction.edittransaction.ChooseCategoryDialogFragment.onCreateDialog(ChooseCategoryDialogFragment.kt:57)
当我导航到带有 RecyclerView 的 DialogFragment 时,会出现此错误。我需要Dialog来包含recyclerview和Room中的自定义项目以供选择。
如果我在 onViewCreated 中初始化了绑定,为什么会遇到这个错误,解决方法是什么?感谢任何帮助
我的对话片段:
@AndroidEntryPoint
class ChooseCategoryDialogFragment : DialogFragment(), ChooseCategoryAdapter.OnItemClickListener {
private val viewModel: ChooseCategoryViewModel by viewModels()
lateinit var binding: FragmentChooseCategoryBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentChooseCategoryBinding.bind(view)
val chooseCatAdapter = ChooseCategoryAdapter(this)
binding.apply {
recyclerView.apply {
adapter = chooseCatAdapter
layoutManager = LinearLayoutManager(requireContext())
setHasFixedSize(true)
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.categories.collect {
val spends = it ?: return@collect
chooseCatAdapter.submitList(spends)
tvNoCategories.isVisible = spends.isEmpty()
recyclerView.isVisible = spends.isNotEmpty()
}
}
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
super.onCreateDialog(savedInstanceState)
return AlertDialog.Builder(requireContext())
.setTitle(requireContext().resources.getString(R.string.choose_category))
.setView(binding.root) // here is the 57th line that error message alludes to.
.setNegativeButton(
requireContext().resources.getString(R.string.cancel_action),
null
)
.create()
}
override fun onItemClick(category: Category) {
// some action with object
}
}