1

I need to know why do we always instantiate a new object of fragment using either A.newInstance() or A() if we know there is already an instance exists. Does it not increase memory uses by the app in Android?

In my case I have an activity and multiple fragments which are opened by menus present in drawer fragment. These fragments further might open other fragments which are not listed in drawer menu. So I am wondering if is it normal to create new instances of secondary fragments by top fragment each time. The same is true for top level fragments. My flow is explained below:

  1. Fragment A (new instance first time)
  2. Fragment B (lower level fragment/new instance, instantiated by A)
  3. Back to A (by pressing up arrow)
  4. Fragment B (lower level fragment/again new instance, instantiated by A)
  5. Back to A (by pressing up arrow)
  6. Fragment X (new instance first time/top level fragment/from drawer menu)
  7. Fragment A (again new instance of A/top level fragment/from drawer menu)

Is it correct to have multiple instances of fragments A (top level / point 7) and B (lower level / point 4)? As I am using this strategy?

Rajan Sharma
  • 103
  • 1
  • 12

1 Answers1

0

You shouldn't instantiate new fragments everytime you "toggle between pages"

You should add them into the FragmentManager when needed with a tag (an optional string parameter), then find them using that tag (findFragmentByTag) , and replace the current shown Fragment if you could find the other. Otherwise, you can instantiate a new one.

You'll also need to place Fragments on the back stack (addToBackStack) , I think, so they are held onto by the FragmentManager

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Some additional details may be here. http://stackoverflow.com/questions/20825600/findfragmentbytag-returns-null-after-perform-a-fragmenttransaction-using-repla – OneCricketeer Jul 31 '16 at 16:52
  • I'm using `add()` as I don't want to call `onCreateView()` method of previous fragment when current fragment is popped out from Backstack. But as per your reply I assume that I need to maintain both `add()` and `replace()` to escape from unnecessarily creating new instances. Also there are no examples of maintaining such things. Every example is demonstrating new Instance implementation. – Rajan Sharma Jul 31 '16 at 17:23
  • At some point you need to initialize an instance, but you should be able to retrieve that instance using a unique tag at a later point, as I explained – OneCricketeer Jul 31 '16 at 17:24
  • Yes I'm using tag through passing `fragment.toString()` as third parameter. One more question, would that retrieved instance be able to obtain new values supplied in `Bundle` and show correct data? – Rajan Sharma Jul 31 '16 at 17:40
  • Not exactly sure on that one. You could always try to `setArguments` with some data after `findFragmentByTag` has returned a non null Fragment – OneCricketeer Jul 31 '16 at 17:43