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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With