0

我正在开发一个活动和多个片段的android应用程序。我的应用包含导航抽屉。它的布局包含listview。点击它的项目,我用ft.replace(R.id.my_placehodler, new MyFragment())动态地改变片段,并将交易添加到backstack ft.addToBackstack(null)。当我每次创建新的事务时都会创建新的事务。在我看来,这不是一个好方法。你能否给我提供关于进行片段交易的正确方法的建议?正确的方法来做片段transacrtion

+0

你看过FragmentManager来切换片段吗? – epsilondelta 2014-12-03 13:28:29

+0

不,我没有。你的意思是我应该跟踪fragmentmanager中的碎片数量吗? – user3816018 2014-12-03 13:29:23

回答

0

只需调用setFragment(FragmentClassObject,false,"fragment");方法即可。

public void setFragment(Fragment fragment, boolean backStack, String tag) { 
    manager = getSupportFragmentManager(); 
    fragmentTransaction = manager.beginTransaction(); 
    if (backStack) { 
     fragmentTransaction.addToBackStack(tag); 
    } 
    fragmentTransaction.replace(R.id.content_frame, fragment, tag); 
    fragmentTransaction.commit(); 
} 
0

如果你想避免instanciating多个实例同一类片段的,那是你想拥有每类片段的单个实例,您可以通过使用标签识别每个片段。

@Override 
public void onNavigationDrawerItemSelected(int position) { 
    String tag = ""; 
    switch (position) { 
    case 0: 
     tag = "fragment_0"; 
     break; 
    case 1: 
     tag = "fragment_1"; 
     break; 
    case 2: 
     tag = "fragment_2"; 
     break; 
    } 

    FragmentManager fragmentManager = getFragmentManager(); 
    Fragment fragment = fragmentManager.findFragmentByTag(tag); 
    if (fragment == null) { 
     // Only in case there is no already instaciated one, 
     // a new instance will be instanciated. 
     switch (position) { 
     case 0: 
      fragment = new Fragment_class_0(); 
      break; 
     case 1: 
      fragment = new Fragment_class_1(); 
      break; 
     case 2: 
      fragment = new Fragment_class_2(); 
      break; 
     } 
    } 

    fragmentManager.beginTransaction().replace(R.id.container, fragment, tag).commit(); 
} 
+0

正如我从你的答复中得到的,我必须将标记设置为片段以便从片段管理器获取它(如果已经实例化)。我对吗? – user3816018 2014-12-03 14:10:55

+0

不只是设置。首先,为同一类设置一个标签(例如,用于Fragment_Class_1的“fragment_0”,用于Fragment_Class_2的“fragment_1”等等)。其次,找到已存在的实例化片段对象(findFragmentByTag)。如果不存在实例化的对象,则该类的新对象将被立即执行。 – hata 2014-12-03 14:41:11