Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the Fragment.newInstance method

I'm implementing an Android fragment. I understand that the framework can automatically destroy and recreate the fragment, and that recreating a fragment calls its default constructor, as opposed to a constructor that has arguments. There are many posts (such as the accepted answer to this question) that show how to provide arguments to the fragment by implementing a static newInstance method.

What I don't understand is who calls newInstance. My first impression was that - since one can define arbitrary arguments for this newInstance method - I should add an explicit call to it somewhere in the app, and that the name newInstance is just a naming convention. But then I would be creating a second fragment in addition to the one created by framework calling the default constructor, which confuses me.

So is the above assumption incorrect, and the newInstance method is really somehow an overload of Java's built-in method for instantiating a class? In that case, I don't see how I can define a newinstance method that takes an arbitrary argument list. Or is that possible in Java, and I just don't know Java well enough?

like image 255
Dabbler Avatar asked Mar 20 '16 11:03

Dabbler


1 Answers

You can name the function however you like: newInstance, getInstance, newFragment. It doesn't matter, it is only a helper method. Important is that you put all your arguments with fragment.setArguments(args). Android system will remember those arguments and will use them when fragment will be recreated.

public static MyFragment newInstance(int arg) {

    Bundle args = new Bundle();
    args.putInt("ARG", arg);

    MyFragment fragment = new MyFragment();
    fragment.setArguments(args);
    return fragment;
}
like image 112
Arkadiusz Konior Avatar answered Sep 22 '22 18:09

Arkadiusz Konior