android-fragments Android片段数据绑定非空getter返回空值

vlf7wbxs  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(132)

根据android文档,为了获得片段中的数据绑定,我使用了一个不可空的getter,但有时候“当我再次尝试访问它时,在我等待用户执行某项操作后,我会收到一个NullPointerException

private var _binding: ResultProfileBinding? = null

private val binding get() = _binding!!

override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,
    savedInstanceState: Bundle?): View? {

    _binding = ResultProfileBinding.inflate(inflater)
    return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
   super.onViewCreated(view, savedInstanceState)

   setupViews()
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

private fun setupViews() {
   
   // On click listener initialized right after view created, all is well so far.
   binding.btnCheckResult.setOnClickListener {

      // There is the crash when trying to get the nonnull binding.
      binding.isLoading = true

   }
}

**有人知道NullPointerException崩溃的原因是什么吗?**我正在努力避免不按照Android文档工作,并且不要返回使用可为空的绑定属性(例如_binding?.isLoading)。还有其他方法吗?

ghhkc1vu

ghhkc1vu1#

我无法解释为什么你在上面的代码中会有任何问题,因为视图的点击侦听器只能在屏幕上被调用,逻辑上必须在onDestroyView()被调用之前。但是,你也问过是否有其他的方法。个人而言,我发现我从来不需要把绑定放在一个属性中,这样就完全避免了整个问题。
你可以用普通的方法膨胀视图,或者使用我在下面的例子中使用的构造函数的快捷方式,这样你就可以跳过覆盖onCreateView函数。然后你可以使用bind()而不是inflate()将绑定附加到现有的视图上,然后在onViewCreated()函数中独占地使用它。当然,我从来没有使用过数据绑定,所以我假设有一个bind函数,就像视图绑定一样。

class MyFragment: Fragment(R.layout.result_profile) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val binding = ResultProfileBinding.bind(view)
            
        // Set up your UI here. Just avoid passing binding to callbacks that might
        // hold the reference until after the Fragment view is destroyed, such
        // as a network request callback, since that would leak the views.
        // But it would be fine if passing it to a coroutine launched using
        // viewLifecycleOwner.lifecycleScope.launch if it cooperates with
        // cancellation.
    }

}

相关问题