为什么在此视图示例中使用get()?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您从文档中的此页面 。
他们的目标是为您提供一种访问
_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 benull
. In the portion of their example that you did not include, they have a comment onbinding
that points out that it can only be used betweenonCreateView()
andonDestroyView()
. If you are in a part of your code where you can guarantee that your code will execute between those two callbacks, you can referencebinding
, which will return the value of_binding
coerced into a not-null
type (ResultProfileBinding
instead ofResultProfileBinding?
).However, if you get it wrong, and you try referencing
binding
beforeonCreateView()
or afteronDestroyView()
, you will crash with aNullPointerException
.Personally, I would avoid this approach.