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开发者_StackOverflow社区?
Fragments are required to have parameterless constructors. This is because fragment instances can be created multiple times. Quoting the docs:
Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().
Unfortunately, you cannot use the suggested setArguments
in 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:
public class MyPortraitFragment extends MyFragment {
public MyPortraitFragment() {
Bundle args = MyFragment.getPortraitArgsBundle();
setArguments(args);
}
}
public class MyLandscapeFragment extends MyFragment {
public MyLandscapeFragment() {
Bundle args = MyFragment.getLandscapeArgsBundle();
setArguments(args);
}
}
You would then use MyLandscapeFragment
or MyPortraitFragment
in your XML, depending on which variant of the fragment you want to use.
精彩评论