I read many articles and StackOverflow answers but still cannot understand why we need a factory method to create an instance of a Fragment.
The following Fragment classes both work fine.
Fragment with two constructors:
public class CtorFragment extends Fragment {
private static final String KEY = "the_key";
public CtorFragment() {
// Android calls the default constructor so default constructor must be explicitly defined.
// As we have another constructor, Android won't create a default constructor for us.
}
public CtorFragment(String s) {
// Set the arguments.
Bundle bundle = new Bundle();
bundle.putString(KEY, s);
setArguments(bundle);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View fragment = inflater.inflate(R.layout.fragment_my, container, false);
TextView textView = (TextView) fragment.findViewById(R.id.textView);
// Use getArguments() to get the String argument set by the constructor with parameter.
textView.setText(getArguments().getString(KEY));
return fragment;
}
}
Fragment with a static factory method:
public class StaticFragment extends Fragment {
private static final String KEY = "the_key";
public static StaticFragment newInstance(String s) {
StaticFragment fragment = new StaticFragment();
// Set the arguments.
Bundle bundle = new Bundle();
bundle.putString(KEY, s);
fragment.setArguments(bundle);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View fragment = inflater.inflate(R.layout.fragment_my, container, false);
TextView textView = (TextView) fragment.findViewById(R.id.textView);
// Use getArguments() to get the String argument set by the constructor with parameter.
textView.setText(getArguments().getString(KEY));
return fragment;
}
}
Can you please explain why everyone (including Google) "strongly recommends" the one with the static factory method? Is there something critical that me and others coming from a non-Android background missing?
Is it that we have to define two methods (constructors) instead of one (static factory method) which causes all the fuss?