Seeking a better pattern for constructing inherited fragments
Problem
Fragments are reborn and reconstructed by the android framework
this results in default constructors. Any initialization that was intended at original birth is accomplished through set arguments and rereading them during rebirth.
This makes it not so obvious to place restrictions on derived classes by their super classes as to what is the set of required arguments for a fragment to work.
One solution based on non-default constructors (it has a flaw)
- Provide both default and non-default constructors
- Have the super-most class register the bundle
- Most-important: Prevent any default constructor from inadvertently invoking the non-default constructor as that will do the setarguments at the wrong time
Almost works, but it has some flaws and assumptions
- You get an android compiler warning
- It depends on how the setArguments() is implemented on the fragment class. If it uses a replication on the bundle, it is too late for the derived classes to alter the bundle. This shifts the burden of registration to the derived classes and you cannot predict the future.
- The most derived class won't be able to supply its arguments in its default constructor and invoke the super classes non default constructor. this forces the derived class to call its constructor a different name (which is not possible) or invent an artificial argument to distinguish it from the default constructor.
Probably a better alternative is
- Rename your non-default constructors as init methods
- Have the derived class inits call base class inits to enforce constraints on what should be in the args bundle
- Those fragments that can be instantiated provide an explicit static newInstance() method
- Look with suspicion if there is a fragment that has a non default constructor (Only exception may be if it is an immediately derived class from a fragment and doesn't need to be further derived)
- Have the newInstance() method call typed init methods on the class that is being instantiated
- If you are further conscious of naming init methods the same, prefix them with class names
I will let you know if the later works in practice...as I am trying now
I will let you know if the later works in practice...as I am trying now
The semantics of setArguments may strongly argue with you to call it after the fragment is constructed...
Depending on the expectation of timing of when it is appropriate to call setArguments, you may be expected to call it after the entire object is constructed, and never as part of the construction, although it seem to work even when done as part of a non-default constructor