添加其他片段到backstack?

时间:2015-10-06 08:05:20

标签: android android-fragments fragment-backstack

我的应用使用5个片段,如下所示:

isAdmin

每个片段都会添加到后面的堆栈中,这样我可以在按下后退按钮的同时返回。但是,当我按下第5个片段上的后退按钮时,我想返回第一个片段,如下所示:

isAdmin

我试着这样做:

Site.Master

当在第4个片段上添加第5个片段时,但是当我按下后退按钮时它仍然会将我发送回第4个而不是第1个片段!以编程方式执行此操作是一种简单的方法吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

In your case, you just need to add first fragment in stack.

No need to add others to stack This could be achieved in following way:

Fragment F1 = new <Fragment Name>();
fragmenttransaction.add(R.id.content,F1).commit();

And for others like F2,F3,F4 & F5 you could use

Fragment F2 = new <Fragment Name>();
fragmenttransaction.replace(R.id.content,F2).addToBackstack(null).commit();

And then you need to override OnBackpressed [inside Activity] like below:

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

Hope it helps!

答案 1 :(得分:0)

you can actually get the backstack count in onBackPressed and check count , if it is 5 then perform popfrombackstack 4 times to get back to 1 fragment