簡體   English   中英

Android 片段 DataBinding 非空 getter 返回 null

[英]Android fragment DataBinding nonnull getter return null

根據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 )。 還有其他方法嗎?

我無法解釋為什么您在上面的代碼中遇到任何問題,因為 View 的點擊偵聽器只能在它在屏幕上時被調用,這在邏輯上必須在onDestroyView()被調用之前。 但是,您還問是否有其他方法。 就個人而言,我發現我從來不需要首先將綁定放在屬性中,這將完全避免整個問題。

您可以改為正常膨脹視圖,或者使用我在下面的示例中使用的構造函數快捷方式,讓您跳過覆蓋onCreateView函數。 然后,您可以使用bind()而不是 inflate( 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.
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM