androidandroid-fragmentskotlinfragment-oncreateview

Fragments without onCreateView


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


Solution

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