我正在尝试理解在片段中使用视图绑定的实现方式,发现与活动不同。
在活动中:
private lateinit var binding: ResultProfileBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ResultProfileBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
在一个片段中:
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
}
现在我的问题是,为什么我们在 fragment 中有 binding
和 _binding
?这一行代码是做什么的,它的目的是什么?
private val binding get() = _binding!!
!!
的可空属性,它是否像使用lateinit一样危险? 在一个项目中,我正在使用lateinit并在一个活动中替换片段,并没有遇到问题。您介意举个例子说明为什么它不安全吗?也许是发出一个请求,在切换片段后尝试更新UI? - JCarlosRlateinit
比单独使用!!
强制属性更安全,因为您不会意外获得NullPointerException。使用单独的!!
强制属性时,必须小心不要在片段销毁后可能被调用的回调中使用它。Google建议使用!!
强制属性,以便在视图销毁时将支持绑定属性更改回null。这可以防止在分离片段期间暂时泄漏绑定中的视图。 - Tenfour04!!
强制属性是过度设计。使用lateinit
更简单,从理论上讲也更安全,尽管如果您在分离状态下访问视图,我会说您很草率。@JCarlosR - Tenfour04