简体   繁体   English

将当前片段添加到后台:Android

[英]Add current fragment to backstack: Android

I am adding a fragment in an activity, fragment A. Now from this fragment, I go to various other fragments, and whenever I go to those, I replace fragment A. 我在活动中添加一个片段,片段A。现在从该片段中转到其他各个片段,每当转到这些片段时,我都将替换片段A。

But there is only one scenario when i want that when i am about to go from fragment A to fragment Z, I add fragment A to the back stack. 但是只有一种情况,当我想要从片段A到片段Z时,我将片段A添加到后堆栈中。 So basically for all the clicks on fragment A, which take the user to other fragments (by replacing fragment A), there is only click where I want that fragment A be put in the back stack, this i want as when i press back from this new fragment Z, I do not want the activity to finish, rather i want fragment A to just come back up. 因此,基本上,对于片段A的所有点击(将用户带到其他片段(通过替换片段A)),只有单击位置,我要将片段A放回堆栈中,这就像我从这个新的片段Z,我不希望活动结束,而是希望片段A重新出现。

Now one dirty way of doing this is to do the following: 现在,执行此操作的一种肮脏方法是执行以下操作:

@Override
public void onBackPressed() {

    if ( getFragmentManager().findFragmentByTag(FragmentZ.class.toString()) == null){
        super.onBackPressed();
    }
    else {
        //i would add fragment A over here.
    }
}

But I was thinking that if i could add fragment A into the back stack just before i go to fragment Z then i do not have to take care of the above. 但是我在想,如果我可以在进入片段Z之前将片段A添加到后堆栈中,那么我就不必照顾上面​​的内容。

Could some please help me with the above? 可以请一些帮助我吗?

The only way you can add Fragment A to the back stack is before you commit the transaction which replaces Fragment A with Fragment Z. 将片段A添加到后堆栈的唯一方法是在提交将片段A替换为片段Z的事务之前。

You can not add it later on after Fragment Z is already added. 在已经添加了片段Z之后,您将无法再添加它。

Before calling commit() on the transaction which inserts Fragment Z, call addToBackStack(null) on the the transaction. 在插入片段Z的事务上调用commit()之前,在事务上调用addToBackStack(null)

Then you will not have to override onBackPressed() . 然后,您将不必重写onBackPressed()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM