9

I'm code reviewing someone else's implementation of a ViewPager. He has an array of fragment class that belongs to each view. Inside getItem(int i) he would write MyFragment.newInstance() which I see no issue with. However, looking at the google doc for ViewPager, they use Fragment.instantiate in their example. Other than the way the class information is setup, is there any design advantage of using instantiate over calling newInstance(arg) or an empty constructor?

Links: Fragment.instantiate

user3063925
  • 255
  • 3
  • 12
  • do you have link that point to instantiate() in the Fragmnet's class? – Blackbelt Feb 12 '14 at 20:12
  • No that thread doesn't answer when I would use Fragment.instantiate. I don't see any reason to ever use this method right now and I want to know if anyone else has come across a situation where they thought using instantiate is the better choice. – user3063925 Feb 12 '14 at 20:22
  • Hmmm... I had never noticed `instantiate()`. The downside of the three-parameter `instantiate()` is that it does not completely solve the problem. While it creates the instance, some other code still has to populate the `Bundle`, and that code has to reside somewhere. A `newInstance()`-style factory method handles both already. Hence, I too don't know why you'd use `instantiate()`, unless you were in a circumstance where you already had the `Bundle` you needed from somewhere else (e.g., it's the extras `Bundle` from an `Intent`). – CommonsWare Feb 12 '14 at 20:23
  • 1
    IMO the linked duplicate does not answer this particular question. Voting to reopen. – laalto Feb 13 '14 at 18:31

1 Answers1

9

instantiate() allows you to specify a fragment by name, without compile-time static resolution of the class.

It's useful when the fragment name comes from some runtime source, such as a binary XML:

<fragment class="com.example.FragmentClass" ...

This is how the framework instantiates fragments specified in layout XML.

In code, it's preferable to use newInstance() or the empty constructor to get compile-time static type checking.

The code instantiate() does under the hood is not too different from what happens when instantiated with newInstance() / empty constructor so there's unlikely to be a significant difference in performance.

laalto
  • 150,114
  • 66
  • 286
  • 303