Search code examples
androidandroid-fragmentsandroid-viewbinding

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)
}

Solution

  • 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.