gpt4 book ai didi

android - 为什么在 Android 绑定(bind)示例中 Google 使用 val 绑定(bind)和 var _binding?

转载 作者:行者123 更新时间:2023-12-02 12:55:57 24 4
gpt4 key购买 nike

示例是 the following :

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
}
为什么使用 var _bindingval binding ,它简单地得到 _binding ,而不是使用 lateinit var binding只要?这个选择背后有什么东西吗?
确实,在 activity's example ,他们实际上使用了 lateinit var :
private lateinit var binding: ResultProfileBinding

override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
binding = ResultProfileBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
为什么无用地使代码复杂化?

最佳答案

这是命名约定,如果您有私有(private) Kotlin 属性,那么您应该以下划线开头。
Kotlin 文档:

Names for backing properties :If a class has two properties which are conceptually the same but one is part of a public API and another is an implementation detail, use an underscore as the prefix for the name of the private property:

class C {
private val _elementList = mutableListOf<Element>()

val elementList: List<Element>
get() = _elementList
}

关于android - 为什么在 Android 绑定(bind)示例中 Google 使用 val 绑定(bind)和 var _binding?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63189584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com