2014-04-29 96 views
0

我有一個ActionBarActivity有一個Navigation Drawer。打開應用程序時,顯示的默認片段是Fragment AonBackPressed與片段不按預期工作

Fragment B(這是導航抽屜上的另一個選擇),有一個ListView,當點擊一個項目時,將在同一個容器中打開Fragment C。當我按下後退按鈕Fragment C,而不是去Fragment B,它會去Fragment A

此外,當我點擊導航抽屜中的物品時,我清除了整個後臺。不知道我是否也這麼做。我已經包含下面的代碼。

不知道爲什麼會發生這種情況!

@Override 
public void onBackPressed() { 
    if (getSupportFragmentManager().getBackStackEntryCount() == 0) { showExitDialog(); } 
    else { super.onBackPressed(); } 
} 

@Override 
public void onNavigationDrawerItemSelected(int position) { 
    // update the main content by replacing fragments 
    FragmentManager fm = getSupportFragmentManager(); 
    switch (position) { 
    case 0:  // User Profile 
     fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 
     fm.beginTransaction().replace(R.id.container, 
       ProfileFragment.newInstance(GlobalMethods.readCurrentUserObject(this)), 
       "profileFragment").commit(); 
     return; 
    case 1:  // Find Match 
     fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 
     fm.beginTransaction().replace(R.id.container, DashboardFragment.newInstance(), "dashboardFragment").commit(); 
     return; 
    case 2:  // Match Settings 
     fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 
     fm.beginTransaction().replace(R.id.container, MatchSettingsFragment.newInstance(), 
       "matchSettingsFragment").commit(); 
     return; 
    case 3:  // Previous Matches 
     fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 
     fm.beginTransaction().replace(R.id.container, PreviousMatchesFragment.newInstance(), 
       "previousMatchesFragment").commit(); 
     return; 
    case 4:  // Messages 
     fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 
     fm.beginTransaction().replace(R.id.container, LatestMessagesFragment.newInstance(), 
       "latestMessagesFragment").commit(); 
     return; 
    case 5:  // Settings 
     return; 
    case 6:  // Log Out 
     startActivity(new Intent(this, LoginActivity.class)); 
     finish(); 
     return; 
    } 
} 

更新1

listView.setOnItemClickListener(new OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      FragmentManager fm = getActivity().getSupportFragmentManager(); 
      android.support.v4.app.FragmentTransaction ft = fm.beginTransaction(); 
      ft.replace(R.id.container, ProfileFragment.newInstance(users.get(position)), "profileFragment"); 
      ft.addToBackStack(null); 
      ft.commit(); 
     } 
    }); 
+0

您可以添加代碼時,應用程序從FragmentB去FragmentC? – araut

+0

@araut添加了將片段從B更改爲C的代碼。 –

+0

試試這個:ft.add(R.id.container,ProfileFragment.newInstance(users.get(position)),「profileFragment」); ft.addToBackStack(引用B); – araut

回答

0

試試這個:

ft.add(R.id.container, ProfileFragment.newInstance(users.get(position)), "profileFragment"); 
ft.addToBackStack(reference to B);