Brian Koey Brian Koey - 5 months ago 40
Android Question

Oncreate call multiple times due to fragment transaction

ffIn Main Activity,

private void navigateTo(int position) {
Log.v(TAG, "List View Item: " + position);

switch(position) {
case 0:
.replace(, new Home(), Home.TAG).commit();
case 1:
case 2:
getSupportFragmentManager().beginTransaction().replace(, History.newInstance(), History.TAG).commit();

When i navigate to my home fragment through navigation drawer(based on the method above), it run onCreate method everytime. From my understanding, fragment cycle should run oncreateview instead oncreate method when you navigate between the screen through navigation drawer(since onpause>oncreateview). Can anyone provide a solution for me that can make sure onCreate only run once?


You are creating new instances each time you call navigateTo.

You should do something like this...

FragmentManager fragManager = getSupportFragmentManager();

// try to find an existing instance
Fragment frag = fragManager.findFragmentByTag(Home.TAG);
if (frag == null) {
   // if none were found, create it
   frag = new Home();

fragManager.beginTransaction().replace(, frag, Home.TAG).commit();