2015-06-11 106 views
0

我在我的活性的導航抽屜和抽屜項點擊片段再次創建,android?

添加片段對於添加片段

Fragment fragment = null; 
    switch (position) { 
     case 0: 
      fragment = new Fragment()1; 
      break; 
     case 1: 
      fragment = new Fragment()2; 
      break; 
     case 2: 
      fragment = new Fragment()3; 
      break; 
     case 3: 
      fragment = new Fragment()4; 
      break; 
     case 4: 
      fragment = new Fragment()5; 
      break; 
     default: 
      break; 
    } 

    if (fragment != null) { 
     FragmentManager fragmentManager = getFragmentManager(); 
     FragmentTransaction ft = fragmentManager.beginTransaction(); 
     ft.replace(R.id.frame_container, fragment); 
     ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 
     ft.addToBackStack(null); 
     ft.commit(); 
     closeDrawer(); 
    } else { 
     Logger.e("MainActivity", "Error in creating fragment"); 
    } 

每當切換從一個片段回視圖再次膨脹作爲在另一片段之前的片段被破壞並且正在被再次創建。

我該如何阻止它被重新創建?

回答

1
Fragment fragment1 = null; 
Fragment fragment2 = null; 
Fragment fragment3 = null; 
Fragment fragment4 = null; 
Fragment fragment5 = null; 
    switch (position) { 
     case 0: 
     if (fragment1 == null) { 
      fragment1 = new Fragment()1; 
     } 
      break; 
     case 1: 
      if (fragment2 == null) { 
      fragment2 = new Fragment()2; 
      } 
      break; 
     case 2: 
      if (fragment3 == null) { 
      fragment3 = new Fragment()3; 
      } 
      break; 
     case 3: 
      if (fragment4 == null) { 
      fragment4 = new Fragment()4; 
      } 
      break; 
     case 4: 
      if (fragment5 == null) { 
      fragment5 = new Fragment()5; 
      } 
      break; 
     default: 
      break; 
    } 

    if (fragment != null) { 
     FragmentManager fragmentManager = getFragmentManager(); 
     FragmentTransaction ft = fragmentManager.beginTransaction(); 
     ft.replace(R.id.frame_container, fragment); 
     ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 
     ft.addToBackStack(null); 
     ft.commit(); 
     closeDrawer(); 
    } else { 
     Logger.e("MainActivity", "Error in creating fragment"); 
    }