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:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new Home(), Home.TAG).commit();
break;
case 1:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
TabbedActivity.newInstance(),
TabbedActivity.TAG).commit();
break;
case 2:
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, 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?

Answer

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(R.id.content_frame, frag, Home.TAG).commit();