本文介绍了Android的FragmentTransaction.addToBackStack混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习片段,得到了有点迷糊的差异 FragmentTransaction.replace(ID,片段,标签) FragmentTransaction.addToBackStack(标签)通话。比方说,我的当前片段是碎裂,然后我装 FragmentB 。我希望,在将来,当我需要加载的碎裂,我没有重新加载它。只是加载旧的老态。我用下面的code段:

I was studying Fragments and got little confused on differentiating FragmentTransaction.replace(id, fragment, tag) and FragmentTransaction.addToBackStack(tag) calls. Lets say that my current fragment is FragmentA and then I loaded FragmentB. I want that in future, when I need to load FragmentA, I don't have to reload it. Just load the old one in old state. I used the following code segment:

public void loadFragment(Fragment fragmentB, String tag) {
    FragmentManager fm = getSupportFragmentManager();
    View fragmentContainer = findViewById(R.id.fragment_container);

    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(fragmentContainer.getId(), fragmentB, tag);

    ft.addToBackStack(tag);

    ft.commit();
}

现在我很迷茫,我应该在哪里添加字符串变量?在更换() addToBackStack()或者在这两个电话?你能解释一下这两个标签地方之间的区别是什么?

Now I am confused, where should I add the string tag? In replace() or in addToBackStack() or in both calls? Can you explain the difference between these two tag places?

推荐答案

你能解释一下这两个标签地方之间的区别是什么?

的文档 addToBackStack 是pretty的明确的:这回堆栈状态,或者为null一个可选的名字

虽然 替换的片段可选的标签名,到后来检索与FragmentManager.findFragmentByTag(串)的片段。

While for replace: Optional tag name for the fragment, to later retrieve the fragment with FragmentManager.findFragmentByTag(String)..

所以,这两个参数是独立的,一是标识后面堆栈,而其他标识中的活动的FragmentManager

So these two parameters are independent, one identifies the back stack, while the other identifies the fragment within Activity's FragmentManager.

您code似乎从这个角度来看正确的,只是我不会搜索 fragmentContainer 查看其身份证,只用那么它的ID替换该片段。使其更简单:

Your code seems correct from this point of view, just that I would not search the fragmentContainer view by its id, only to use then its id for replacing the fragment. Make it simpler:

public void loadFragment(Fragment fragmentB, String tag) {
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(R.id.fragment_container, fragmentB, tag);

    ft.addToBackStack(null);

    ft.commit();
}

如果你不需要后来确定这回堆栈,null传递 addToBackStack 。至少我总是这样做。

In case you don't need to identify this back stack later on, pass null for addToBackStack. At least I'm always doing it.

这篇关于Android的FragmentTransaction.addToBackStack混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:32