Brian Koey Brian Koey - 1 year ago 105
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?

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download