在底部工作表对话框中
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
后删除可运行程序之前调用它??
我不知道为什么!
在绑定为null之前删除处理程序回调正确的方式
override fun onDestroyView() {
super.onDestroyView()
handler?.removeCallbacks(this)
_binding = null
}
您应该使用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>
第页。S.总是在类名的末尾命名你的类别,以便于搜索和维护