Yalla T.
Yalla T.

Reputation: 3727

How to create a Fragment instance correctly in Android

I have seen different ways to create a Fragment. Can somebody clear me up whats the difference between the methods and what is the best way and when to use which.

  1. new MyFragment() I myself use this, because it seemed natural to me.
  2. MyFragment.instantiate(Context context, String fname, Bundle args) This looks like a custom static method to create a Fragment but i've never seen it used.
  3. My.Fragment.newInstance() This one is in an Android Developer Example.

What's each options purpose?

Upvotes: 2

Views: 4962

Answers (1)

Anis BEN NSIR
Anis BEN NSIR

Reputation: 2555

The most difference is when to use each sample:

1- Creates a new fragment object each time called.

2- Same as calling the empty constructor, but, if you set the fragment to setRetainInstance(true), this will not work if you use the empty constructor.

3- My.Fragment.newInstance(), method to get the single instance from a static fragment, If you have a static class extending fragment, you can create a Method to return a new fragment or the current fragment, its the singleton pattern.

4- Inflate from xml, same as calling the empty contructor, the Android FrameWork take care of attachement to the view, but the instance will be kept with the hole activity lifecycle, needs more memory and cannot be reused multiple time.

Upvotes: 4

Related Questions