【发布时间】:2021-06-23 01:34:36
【问题描述】:
kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
at space.rodionov.financialsobriety.ui.transaction.edittransaction.ChooseCategoryDialogFragment.onCreateDialog(ChooseCategoryDialogFragment.kt:57)
当我导航到包含 RecyclerView 的 DialogFragment 时,会出现此错误。我需要 Dialog 来包含可从 Room 中选择自定义项目的回收站视图。
如果我在 onViewCreated 中初始化了绑定,为什么会遇到这个错误,解决方法是什么? 感谢任何帮助
我的 DialogFragment:
@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
}
}
【问题讨论】:
-
据我所知,
onCreateDialog被称为 之前onViewCreated。但是,您可以通过调试/日志轻松验证这一点。 -
感谢您的帮助,我将初始化重新定位到
onCreateDialog()并且它工作正常。
标签: android kotlin android-dialogfragment android-viewbinding fragment-oncreateview