-1
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
    }
}
4

1 回答 1

1

尝试使用以下代码,它将帮助您,onCreateDialog() 在 onViewCreated 之前执行,此时您的视图未创建。

 lateinit var binding: FragmentChooseCategoryBinding

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    _binding = FragmentChooseCategoryBinding.inflate(LayoutInflater.from(context))
    return AlertDialog.Builder(requireActivity())
        .setView(binding.root)
        .create()
}

override fun onDestroyView() {
    super.onDestroyView()
    binding = null
} 
于 2021-06-23T02:29:38.387 回答