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