Why instantiate a new fragment inside a public static class

Ref: Snippets Documentation

I am new to Java and Android and am looking at an online Android manual. I have two questions:

Question 1: Why is it necessary to create a new instance of DetailFragment within a public static class?

Question 2: "Create new instance" next declares a new DetailFragment. In general, there are four places where the same name "DetailFragment" is used. This is very confusing. Explain, please?

public static class DetailsFragment extends Fragment {

    /* Create a new instance of DetailsFragment, initialized
       to show the text at 'index'. */

    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);

        return f;



source to share

2 answers

This is called static factory method

, in which case it makes it easy to create a new instance of the fragment with all the required arguments filled in without knowing the internal implementation. For example, without this, to create a properly initialized instance of a fragment, you should use:

DetailsFragment fragment = new DetailsFragment();
Bundle args = new Bundle();
args.putInt("index", index);
// Then use the fragment however you need it


Using a static factory method, all this logic is integrated into the fragment itself and you can simply use:

DetailsFragment fragment = DetailsFragment.newInstance(index);
// Then use the fragment




The best practice for fragments is to use a static method newInstance()

, because the Android system needs (and will use) an empty public constructor to create your fragment in many cases.

For example, if you show DetailsFragment

and the user locks their device and returns after half an hour, Android will try to recreate the state of your app and when it needs to re-instantiate DetailsFragment

it will use an empty public constructor.

Fragments, however, do support arguments using setArguments(Bundle)

. Thus, instead of a constructor, you can use a static method newInstance()

to set the arguments required to recreate the fragment.

In this example DetailsFragment

, when Android re-creates the fragment, the variable index

will still be available to the fragment by calling getArguments().getInt("index")

. If you created a variable index

in the constructor, this information will be lost when the fragment is restored.



All Articles