【问题标题】:How to correctly use Android View Binding in DialogFragment?如何在 DialogFragment 中正确使用 Android 视图绑定?
【发布时间】:2020-04-14 10:05:31
【问题描述】:

在 DialogFragment() 中使用 Android 视图绑定的正确方法是什么?

官方文档只提到了Activity和Fragment: https://developer.android.com/topic/libraries/view-binding

【问题讨论】:

    标签: android dialogfragment android-viewbinding


    【解决方案1】:

    请改用inflate(LayoutInflater.from(context))。并使用binding.root 设置构建器视图。

    此外,正如 Google 所建议的,在使用片段时,最好将 binding 实例在 onDestroyView() 处设置为 null: https://developer.android.com/topic/libraries/view-binding#fragments

    例子:

    class ExampleDialog : DialogFragment() {
    
        private var _binding: DialogExampleBinding? = null
        // This property is only valid between onCreateDialog and
        // onDestroyView.
        private val binding get() = _binding!!
    
        override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
            _binding = DialogExampleBinding.inflate(LayoutInflater.from(context))
            return AlertDialog.Builder(requireActivity())
                .setView(binding.root)
                .create()
        }
        
        override fun onDestroyView() {
            super.onDestroyView()
            _binding = null
        } 
    }
    

    【讨论】:

    • 建议这样做是为了防止崩溃,但是如果绑定设置为空后使用会发生什么?我认为它会崩溃,这意味着private val binding get() = _binding!! 完全没有意义。我错过了什么吗?
    • 一旦视图到达 onDestroyView 生命周期,您不应该使用它。
    • 另外,将绑定用作局部变量是一种更好的做法。在这种情况下无需覆盖 onDestroyView ! :)
    猜你喜欢
    • 1970-01-01
    • 2012-07-03
    • 2020-07-29
    • 1970-01-01
    • 2020-06-04
    • 2017-06-19
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    相关资源
    最近更新 更多