Android中的popBackStack和addToBackStack

时间:2016-03-19 21:07:38

标签: android android-fragments fragment-backstack

我是android的新手并尝试将我的iphone应用程序转换为android。我尝试在片段之间进行控制,并且在从片段A导航到B之后,我想要使用后退按钮从片段B返回到A.我做了一个研究,但不能很好地理解它。下面的代码我有一个导航抽屉,我在其中导航片段。点击关注者后,我想使用后退按钮返回新闻Feed。

//this is the navigation drawer part     
if (id == R.id.my_archive_drawer) {

                myArchiveFragment fragment = new myArchiveFragment();
                android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, fragment);
                fragmentTransaction.addToBackStack("newsFeedFragment");
                fragmentTransaction.commit();

            } else if (id == R.id.followers_drawer) {

                followedFollowersFragment fragment = new followedFollowersFragment();
                android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, fragment);
                fragmentTransaction.addToBackStack("newsFeedFragment");
                fragmentTransaction.commit();

            } 
//this is the navigation drawer part   



//this is the on create part part   
        newsFeedFragment fragment = new newsFeedFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
//this is the on create part part  


//onbackpreseed part
   public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            getFragmentManager().popBackStack("newsFeedFragment");
        }
    }
//onbackpressed part

1 个答案:

答案 0 :(得分:1)

addToBackStack意味着将片段放入堆栈中。这意味着当您将片段新闻推送到片段关注者时,您将向片段添加片段。所以当你回去时你会回到新闻片段。

试试这段代码:

followedFollowersFragment fragment = new followedFollowersFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

然后在你的onBackPressed()中删除popbackstack(),因为当你调用onBackPressed单击后退按钮时,你已经删除了追随者片段。所以onBackPressed()应该是这样的:

 @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种方法的更多信息,请阅读here