Reputation: 6451
In my Fragment
I have a static newInstance
method which takes some arguments, puts them in the Bundle
, creates new Fragment
with this Bundle
:
public static Fragment newInstance(final CommandWithNumber command) {
final CallsFragment fragment = new CallsFragment();
final Bundle args = new Bundle();
args.putSerializable(SHOW_DETAILS_COMMAND, command);
fragment.setArguments(args);
return fragment;
}
Is there a way to prevent calling new CallsFragment()
in other places in the code and force developers to use newInstance
method?
Of course, I can't make CallsFragment
private because OS needs public one. Maybe there is a way to show warning or so, if someone tries to create an instance with the constructor?
Upvotes: 2
Views: 185
Reputation: 12587
you should NOT be using a Fragment's constructor for anything, the system uses it for restoring configuration changes. there must be a public constructor that takes no arguments in a Fragment class
All subclasses of Fragment must include a public no-argument constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the no-argument constructor is not available, a runtime exception will occur in some cases during state restore.
from the Documentation
EDIT: after discussing this further in the comment section and understanding what you want to do, you should add a @Deprecated
annotation with javadocs saying why you shouldn't use this constructor internally, something like this:
/**
* this should <b>NEVER</b> be used, always use the newInstance method instead
**/
@Deprecated
public CallsFragment() {
// EMPTY METHOD
}
Upvotes: 5