【问题标题】:difference between two declaration and one declaration binding in fragment片段中两个声明和一个声明绑定之间的区别
【发布时间】:2021-07-10 14:02:00
【问题描述】:

在提问之前我想说我已经阅读了this post

正如谷歌文档所说: this link

你应该使用这个结构来声明绑定对象(_bindingbinding):

private var _binding: ResultProfileBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = ResultProfileBinding.inflate(inflater, container, false)
    val view = binding.root
    return view
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

我想知道,我们是否可以将这个结构与一个声明绑定一起使用?它的工作原理是一样的吗?如果没有,为什么不呢?

class MyFragment: Fragment(R.layout.my_fragment_layout) {

    private var binding: MyFragmentLayoutBinding? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        binding = MyFragmentLayoutBinding.inflate(inflater, container, false)

        return binding!!.root
    }



    override fun onDestroy() {
        super.onDestroy()

        //to prevent from memory leaks
        binding = null
    }
}

【问题讨论】:

  • 第一个只是为非空属性使用可为空的支持字段。这意味着如果在有效状态下访问binding,则无需不断检查可空性或将其强制转换为非空。

标签: android kotlin fragment android-viewbinding


【解决方案1】:

这可以正常工作,但这意味着您必须处理在整个课程中访问该属性的绝大多数时间都可以为空的问题。

在绝大多数情况下,!! 是代码异味。但是在绑定的情况下,在视图生命周期期间调用的任何代码中使用!! 是有效的。由于这种情况发生在 Fragment 代码中的很多地方,因此创建一个不可为空的属性更简洁,因此您的代码中只有一个地方使用 !!

也许比!! 更好,你可以这样写一个有用的错误信息:

private var _binding: ResultProfileBinding? = null
private val binding: ResultProfileBinding get() = _binding 
    ?: error("Cannot access binding except between between onCreateView and onDestroyView")

但在您习惯了生命周期的工作方式之后,这可能会有点过头了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-25
    • 2020-02-07
    • 2020-04-20
    • 2011-05-23
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2010-09-19
    相关资源
    最近更新 更多