2

recently i saw some articles about inflating the fragment layout directly from the Fragment()

class ExampleFragment: Fragment(R.layout.example_fragment)

does this stand only for fragments that dont hold any data and interaction, when should we use this method

ardritkrasniqi
  • 739
  • 5
  • 13

1 Answers1

3

This was added in androidx.fragment version 1.1.0:

Fragment LayoutId constructor: Subclasses of Fragment can now optionally call into a constructor on Fragment that takes an R.layout ID, indicating the layout that should be used for this fragment as an alternative to overriding onCreateView(). The inflated layout can be configured in onViewCreated().

So in essence it's a shorthand for overriding onCreateView() that just inflates a layout and returns it, and encourages a style of configuring the view in onViewCreated() rather than onCreateView().

laalto
  • 150,114
  • 66
  • 286
  • 303
  • If there's a configuration change, then the fragment manager is going to instantiate a new copy of your class through your sole empty constructor, which will pass the same layout ID to the superconstructor. I don't see a problem with that. – Tenfour04 Jan 24 '20 at 16:50
  • @Tenfour04 You're right, thanks. Will update the answer. – laalto Jan 24 '20 at 16:53
  • 1
    Is it possible to instantiate databinding in onviewcreated – ardritkrasniqi Jan 25 '20 at 07:23
  • override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) _binding= FragmentFirstBinding.bind(view)} – Vela Sep 23 '21 at 14:20