Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is better to use View Binding in Fragments? (onCreateView vs onViewCreated)

I saw some examples where binding were defined and used in onCreateView() using inflate() and in onViewCreated() using bind().

What's the difference? And where is it better to operate with our views(RecyclerView, TextView and so on)?

Google documentation shows example like this:

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

But also in some articles we can see something like this:

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

    _binding = ResultProfileBinding.bind(view)
}
like image 216
MrArtyD Avatar asked Oct 16 '25 15:10

MrArtyD


1 Answers

It's good practice to use initialize binding in onCreateview as its will inflate the layout the same moment the view creates and then use this inside onViewCreated and other functions.

Also you need to make _binding = null in onDestroyView to prevent the leaks.

like image 60
Dheeraj Kotwani Avatar answered Oct 18 '25 09:10

Dheeraj Kotwani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!