gpt4 book ai didi

android - 为什么不在 Android Fragment View 绑定(bind)中使用 lateinit 修饰符?

转载 作者:行者123 更新时间:2023-12-05 00:18:01 24 4
gpt4 key购买 nike

android documentation我们有没有 lateinit 的 View 绑定(bind)示例:

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
}

为什么我们不使用 lateinit,就像我们在 Activity 中使用它一样:

private lateinit var binding: ResultProfileBinding? = null

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = ResultProfileBinding.inflate(inflater, container, false)
return binding.root
}

我怀疑它有内存泄漏问题。你能解释一下吗?

最佳答案

我找到了一个很好的解释here .

解释的 fragment :

How do leaks happen in fragments? First, we need to start by reviewingthe important nuance of fragments. They have two different lifecycles:

  • It’s own lifecycle (onCreate and onDestroy)
  • It’s view’s lifecycle (onCreateView and onDestroyView)

Having two lifecycles for a singlescreen can be problematic. They are created and destroyed at differenttimes, for instance, when putting a fragment on the back-stack.Specifically, holding onto views after onDestroyView is called willleak. This happens when a fragment is on the back stack, and althoughits view is destroyed, the fragment itself is not. The garbagecollector is unable to clear the reference to those views.

还有来自 this 的一个 fragment 堆栈溢出答案:

You have to null out your references to the views in onDestroyView asthat's the sign that the view is no longer being used by the Fragmentsystem and it can be safely garbage collected if it wasn't for yourcontinued reference to the View.

关于android - 为什么不在 Android Fragment View 绑定(bind)中使用 lateinit 修饰符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70065804/

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