为什么在此视图示例中使用get()?

发布于 2025-01-21 20:13:58 字数 449 浏览 0 评论 0原文

 private var _binding: ResultProfileBinding? = null
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
}

I want to know why "private val binding get() = _binding!!" was used here?

 private var _binding: ResultProfileBinding? = null
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
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绾颜 2025-01-28 20:13:58

我假设您从文档中的此页面

他们的目标是为您提供一种访问_binding值的方法,而无需处理_binding可以是null。在您未包含的示例的部分中,他们对binding有评论,指出它只能在oncreateview()ondestroyview之间使用。 ()如果您处于代码的一部分中,您可以在其中保证您的代码将在这两个回调之间执行,您可以参考binding,将返回_binding的值被胁迫到NOT- null type(result ProfileBinding而不是result ProfileBinding?)。

但是,如果您弄错了,然后尝试在oncreateview()或之后 ondestroyview()之前尝试引用binding代码> NullPoInterException 。

就个人而言,我会避免这种方法。

I am assuming that you got that code from this page in the documentation.

Their objective is to give you a way to access the _binding value without needing to deal with the fact that _binding can be null. In the portion of their example that you did not include, they have a comment on binding that points out that it can only be used between onCreateView() and onDestroyView(). If you are in a part of your code where you can guarantee that your code will execute between those two callbacks, you can reference binding, which will return the value of _binding coerced into a not-null type (ResultProfileBinding instead of ResultProfileBinding?).

However, if you get it wrong, and you try referencing binding before onCreateView() or after onDestroyView(), you will crash with a NullPointerException.

Personally, I would avoid this approach.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文