android 视图绑定返回null

9vw9lbht  于 2023-05-05  发布在  Android
关注(0)|答案(2)|浏览(205)

在“底部图纸”对话框中

class XBottomSheet () : BottomSheetDialogFragment() {

    private var _binding: XBottomSheetBinding? = null
    private val binding get() = _binding!!
    private var handlerRunner: Runnable? = null
    private val handler = Handler(Looper.getMainLooper())

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

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

        handlerRunner = Runnable {
            binding.tvTimeOffer.text = "text"
       }
       
       handler.postDelayed(handlerRunner!!, 1)
    }

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

        handlerRunner?.apply {
            handler.removeCallbacks(this)
        }
    }
}

在某些手机Firebase carashlytics日志private val binding get() = _binding!!非致命异常:java.lang.NullPointerException
在某些时候,处理程序可以在设置_binding = null后删除runnable之前调用它吗??
我不知道为什么!

qgelzfjb

qgelzfjb1#

在绑定为null之前删除处理程序回调

override fun onDestroyView() {
        super.onDestroyView()
        handler?.removeCallbacks(this)
        _binding = null
    }
zdwk9cvp

zdwk9cvp2#

您应该改用DataBinding

class XBottomSheetFragment () : BottomSheetDialogFragment() {

private lateinit var binding: XBottomSheetBinding
private var handlerRunner: Runnable? = null
private val handler = Handler(Looper.getMainLooper())

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

binding = DataBindingUtil.inflate(inflater, R.layout.fragment_x_bottomsheet, container, false)
        return binding.root
}

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

    handlerRunner = Runnable {
        binding.tvTimeOffer.text = "text"
   }
   
   handler.postDelayed(handlerRunner!!, 1)
}

override fun onDestroyView() {
    super.onDestroyView() 

    handlerRunner?.apply {
        handler.removeCallbacks(this)
    }
}

}
在xml布局中,通过布局标记封装您的工作:

<layout>
<--- your layout design --->
</layout>

P.S.总是在你的类名的末尾命名你的类的类别,以便于搜索和维护

相关问题