始终返回主片段onBackpressed

时间:2016-12-19 09:44:22

标签: android android-fragments navigation back-stack

我在Activity中实现了导航抽屉。我的应用程序中有3-4个片段。

让我们说有3个片段: Fragment_1,Fragment_2,Fragment_3

当我启动我的应用程序时,Fragment_1已加载,我使用导航抽屉转到另一个片段。

所以它就像

Fragment_1 - > Fragment_2 - > Fragment_3 - > Fragment_1 - > Fragment_3

现在,当我按下后退按钮时,它就像

Fragment_3 - > Fragment_1 - > Fragment_3 - > Fragment_2 - > Fragment_1

  

但是,我想要的东西,如果我在哪里,当我按回键,我   始终导航回Fragment_1。

我使用下面的代码导航到另一个片段: -

nav_menu_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        switch (position) {
            case 0:
                DashboardFragment dashboardFragment = new DashboardFragment();
                fragmentTransaction.replace(R.id.mainContainer, dashboardFragment, dashboardFragment.getClass().getName());
                break;

            case 1:
                ProfileFragment profileFragment = new ProfileFragment();
                fragmentTransaction.replace(R.id.mainContainer, profileFragment, profileFragment.getClass().getName());
                fragmentTransaction.addToBackStack(null);
                break;

            case 2:
                ContactUsFragment contactUsFragment = new ContactUsFragment();
                fragmentTransaction.replace(R.id.mainContainer, contactUsFragment, contactUsFragment.getClass().getName());
                fragmentTransaction.addToBackStack(null);
                break;

            case 3:
                AboutUsFragment aboutUsFragment = new AboutUsFragment();
                fragmentTransaction.replace(R.id.mainContainer, aboutUsFragment, aboutUsFragment.getClass().getName());
                fragmentTransaction.addToBackStack(null);
                break;

            default:
                break;
        }
        fragmentTransaction.commit();
        drawer.closeDrawer(GravityCompat.START);
    }
});

请帮忙......

2 个答案:

答案 0 :(得分:1)

@Override
    public void onBackPressed() {

        if(!(getSupportFragmentManager().findFragmentById(R.id.mainContainer) instanceof DashboardFragment))
        {
            DashboardFragment dashboardFragment = new DashboardFragment();
            fragmentTransaction.replace(R.id.mainContainer, dashboardFragment, dashboardFragment.getClass().getName());
        }else {
            super.onBackPressed();
        }
    }

将此方法用于主要活动将解决您的问题。

答案 1 :(得分:0)

我已经更改了代码中的下几行,效果很好

替换:

fragmentTransaction.replace(R.id.mainContainer, dashboardFragment, 
dashboardFragment.getClass().getName());

使用:

getSupportFragmentManager().beginTransaction().replace(R.id.mainContainer,
dashboardFragment).commit();