binding 和 _binding 有什么区别? [英] What is the difference between binding and _binding?

查看:64
本文介绍了binding 和 _binding 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解片段中视图绑定的实现,但我发现它与活动不同.

I am trying to understand the implementation of view binding in a fragment and I found that it is different from an activity.

在活动中:

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
}

现在我的问题是,为什么片段中有 binding_binding ?这条线是做什么的,它的目的是什么?

Now my question is, why do we have binding and _binding in the fragment? What is this line is doing and what is it's purpose?

private val binding get() = _binding!!

推荐答案

在第二个示例中,_binding 属性可以为空,以便在初始化"之前允许状态.然后 binding 属性有一个 getter 来提供方便的访问,因为支持字段 (_binding) 已经初始化.

In the second example, the _binding property is nullable so as to allow a state before it has been 'initialised'. Then the binding property has a getter to provide convenient access, given that the backing field (_binding) has been initialised.

您所指的特定行意味着当您尝试访问 binding 时,它将返回 _binding.然而,空断言运算符(!!)添加了额外的断言,即 _binding 不为空.

The specific line you're referring to means that when you try to access binding, it will return _binding. However the null assertion operator (the !!) adds the extra assertion that _binding isn't null.

实际上,您所做的一切只是创建了一个与 lateinit 属性类似的东西,实际上,如果您查看 lateinit 声明的反编译字节码,它们实际上是相同的.

Really all that you've done is created an analogue of the lateinit property, and actually if you look at the decompiled bytecode of a lateinit declaration, they amount to the same.

然而,正如@Tenfour04 指出的,这里的细微差别是第二种方法允许您将支持字段设置回 null,而您不能使用 lateinit 属性.当您在片段中使用绑定时,建议将 onDestroyView 中的绑定清除,以避免内存泄漏,这就是他们在片段中采用这种方法的原因.

However, as @Tenfour04 pointed out, the subtle difference here is that the second approach allows you to set the backing field back to null, whereas you can't do this with a lateinit property. When you use a binding in a fragment, it's recommended to null out the binding in onDestroyView in order to avoid memory leaks, so this is why they've gone with this approach in a fragment.

这篇关于binding 和 _binding 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆