片段返回指定的片段

时间:2018-03-13 05:15:39

标签: android android-fragments onbackpressed

我正在使用片段开发一个Android应用程序。我有五个片段。那些是A,B,C,D,E。我的第一个片段A是主片段。首先我从A到B然后从B到C遍历。在C中,当我按下后退按钮时,我希望它返回到A.我使用下面的代码从A调用B片段。同样的方法用于调用另一个片段。

FragmentB fragment = new FragmentB();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction().addToBackStack("tag");
transaction.replace(R.id.content_frame, fragment);
transaction.commit();

活动中的后退按钮代码如下

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }

}

如何解决这个问题请帮帮我。

2 个答案:

答案 0 :(得分:1)

试试这个:

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawers();
        return;
    }

    // This code loads home fragment when back key is pressed
    // when user is in other fragment than home
    if (shouldLoadHomeFragOnBackPress) {
        // checking if user is on other navigation menu
        // rather than home
        if (navItemIndex != 0) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
            return;
        }
    }

    super.onBackPressed();
}

请参阅此参考:https://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/

答案 1 :(得分:1)

你可以试试这个:

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    }    FragmentManager fragmentManager = getSupportFragmentManager();
    int backCount = fragmentManager.getBackStackEntryCount();
    System.out.println("back count " + backCount);

    if(backCount==0)
    {
        actionBar.setTitle("Home");
       //Here you can show alert dialog for exit the app?
    }
  /*  else if(backCount==1)
    {

    }*/
    else if(backCount==1)
    {
        fragmentManager.popBackStack();
        // setTitle("Home");
        navigationView.getMenu().getItem(0).setChecked(true);
        actionBar.setTitle("Home");
    }
    else if(backCount>1)
    {

        for(int i=fragmentManager.getBackStackEntryCount();i>=1;i--)
        {
            fragmentManager.popBackStack();
            System.out.println("back count loop" + fragmentManager.getBackStackEntryCount());
        }
        actionBar.setTitle("Home");
    }
}