Search code examples
androidconstructorandroid-dialogfragment

Why use newInstance for DialogFragment instead of the constructor?


Looking at the documentation of DialogFragment, one sees the static newInstance method to initialize a new alert dialog fragment. My question is, why not use a constructor to do so, like this:

public MyAlertDialogFragment(int title) {
    Bundle args = new Bundle();
    args.putInt("title", title);
    setArguments(args);
}

Isn't this exactly the same or does it differ somehow? What's the best approach and why?


Solution

  • If you overload the constructor with MyAlertDialogFragment(int title), the Android system may still call the default MyAlertDialogFragment() constructor if the Fragment needs to be recreated and the parameter is then not passed.