Before asking question I want to say I have read this post
As google document said in: this link
you should use this structure to declare binding object (with both _binding
and binding
) :
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
}
I want to know, If we can use this structure with one declaration binding instead? does it work the same? If No, why not?
class MyFragment: Fragment(R.layout.my_fragment_layout) {
private var binding: MyFragmentLayoutBinding? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = MyFragmentLayoutBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onDestroy() {
super.onDestroy()
//to prevent from memory leaks
binding = null
}
}