onBackPressed与Fragments无法正常工作

时间:2014-04-29 23:17:13

标签: android android-fragments back-button back-stack

我的ActionBarActivity有一个Navigation Drawer。打开应用时,显示的默认片段为Fragment A

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();
        }
    });

1 个答案:

答案 0 :(得分:0)

试试这个:

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