I’m writing a class which extends Fragment and I would like to use it in an XML file. For my class I have a constructor which takes one parameter which specifies how the fragment should layout its UI.
I would like to use my class in XML but would also like to specify this layout parameter as well but is it possible to include it in the XML?
Fragments are required to have parameterless constructors. This is because fragment instances can be created multiple times. Quoting the docs:
Unfortunately, you cannot use the suggested
setArgumentsin the XML but it might be possible to do it differently, depending on what possible set of arguments you are planning to pass to your fragment. You can, for example, subclass your fragment appropriately:You would then use
MyLandscapeFragmentorMyPortraitFragmentin your XML, depending on which variant of the fragment you want to use.