I recently read the StackOverflow above about the fragment instantiation of a problem, I think it is very interesting.
What is the difference between new Myfragment () and myfragment.newinstance () ? Which one should I use?
Good question. The answer is that the title of this article suggests that this is a reasonable design. In this case, thenewinstance () method is a "static Factory method", which allows us to omit the constructor and the extra setter method when initializing and setting up a new fragment. It is a good practice to provide a static factory method for your Fragment , as it encapsulates and abstracts the steps required to construct the object on the client. For example, consider the following code:
1 Public classMyfragmentextendsFragment {2 3 /**4 * The static factory method requires a value of type int to initialize the parameters of the fragment,5 * Then return the new fragment to the caller6 */7 Public StaticMyfragment newinstance (intindex) {8Myfragment f =Newmyfragment ();9Bundle args =NewBundle ();TenArgs.putint ("Index", index); One f.setarguments (args); A returnF; - } -}
Do not let the client call the default constructor, and then manually set the fragment parameters. We directly provide them with a static factory approach. This is better than calling the default constructor method, there are two reasons: one is that it is convenient for others to call. Another is to ensure that the fragment build process is not error-prone. By providing a static factory approach, we avoid making mistakes-we no longer have to worry about accidentally forgetting to initialize fragmnet parameters or not setting parameters correctly.
Overall, although the difference between the two lies in the design, but the difference between them is very big. Because providing a static factory method has an upward abstraction of a level, it makes the code easier to understand.
Note : It is also important to provide a static factory instead of using the default constructor or defining a parametric constructor yourself. Fragmnet are often destroyed and re-instantiated, and the Android framework calls only fragment parameterless constructors. You have no way to intervene when the system automatically instantiates fragment. Some parameters that require an external pass-through are not able to be initialized. Using the static factory method, the externally passed-in parameters can be saved by fragment.setargument on its own, so that we can be in the Fragment.oncreate (...). These parameters are taken out when the call is made.
SOURCE Link: Using newinstance () to instantiate a Fragment
"Translate" uses newinstance () to instantiate fragment