android - 带 null 参数的 addToBackStack 是什么意思?

标签 android android-fragments

我有一个客户代码。所有 fragment 只有一个 Activity ,即单个 Activity 正在管理所有 fragment 。

此 Activity 包含该 fragment 方法末尾的任何 fragment 的以下代码-

例如—— fragment MoreFragment:

MoreFragment firstFragment = new MoreFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.article_fragment, firstFragment)
.addToBackStack(null).commit();

所以,

1) addToBackStack(null) 后跟 commit() 是什么意思?

2) 为什么需要向 addToBackStack 传递一个空参数?

3)这样添加后如何获取该 fragment ?

似乎这段代码没用,因为我在没有最后一行 .addToBackStack(null).commit() 的情况下运行了代码,并且运行没有任何问题。

最佳答案

What is the meaning of addToBackStack(null) followed by a commit()?

引用文档:

By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button.

If you add multiple changes to the transaction (such as another add() or remove()) and call addToBackStack(), then all changes applied before you call commit() are added to the back stack as a single transaction and the Back button will reverse them all together.

向 FragmentTransaction 添加更改的顺序无关紧要,除了:

您必须最后调用 commit()。如果您将多个 fragment 添加到同一个容器,那么您添加它们的顺序决定了它们在 View 层次结构中出现的顺序。

所以你必须在最后提交。

Why you need to pass a null parameter to addToBackStack?

它不需要为空,它可以是一个字符串。如果你不想要,只需传递 null。

public abstract FragmentTransaction addToBackStack (String name)

Added in API level 11 Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.

Parameters name An optional name for this back stack state, or null.

关于:

Seems like this code is useless as I ran the code without the last line .addToBackStack(null).commit() and it ran without any problems

如果您想导航到上一个 fragment ,请将其添加到 backstack。所以这取决于您是否要将 fragment 添加到后台堆栈。

How to get that fragment after being added like this?

您已经拥有 fragment 实例 firstFragment。所以我不知道你说的稍后获取 fragment 是什么意思。

更多信息@

http://developer.android.com/guide/components/fragments.html

http://developer.android.com/reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String)

关于android - 带 null 参数的 addToBackStack 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22984950/

相关文章:

android - 如何在 TextView 中轻松创建指向 Activity 的超链接(有 Intent )

Android - Fragment 和 Activity 的关系

android - fragment 无法转换为 android.app.activity

android - 检测隐藏 fragment 中的 View 可见性

Android fragment 布局帮助

android - 在 View 页面中不显示图像 slider 在 android 中

java - 是否有支持 NIST 标准的随机生成器的 Java 8 实现?

android - 删除警报对话框边框android

android - TextInputLayout 新增了对字符计数的支持

android - HTTP/2 来了。原生 Android 应用程序如何利用它?