调用这些方法的主要区别是什么:
fragmentTransaction.addToBackStack(name);
fragmentTransaction.replace(containerViewId, fragment, tag);
fragmentTransaction.add(containerViewId, fragment, tag);
替换一个已经存在的片段,并将一个片段添加到活动状态,并将一个活动添加到后台堆栈,这意味着什么?
其次,使用findFragmentByTag(),是否搜索由add()/replace()方法或addToBackStack()方法添加的标记?
FragmentManger的添加和替换功能可以这样描述
1. 添加意味着它会将片段添加到片段返回堆栈中,并在您提供的给定帧中显示
就像
getFragmentManager.beginTransaction.add(R.id.contentframe,Fragment1.newInstance(),null)
2.替换意味着你在给定的帧中用另一个片段替换这个片段
getFragmentManager.beginTransaction.replace(R.id.contentframe,Fragment1.newInstance(),null)
两者之间的主要实用程序是,当你回堆叠时,replace将刷新片段,而add将不会刷新之前的片段。
下面的图片显示了add()和replace()之间的区别
因此add()方法继续在FragmentContainer中的前一个片段之上添加片段。
replace()方法清除容器中所有之前的Fragment,然后将其添加到FragmentContainer中。
什么是addToBackStack
addtoBackStack方法可以与add()和replace方法一起使用。它在Fragment API中有不同的用途。
目的是什么?
片段API与活动API不同,默认情况下没有返回按钮导航。如果你想回到之前的Fragment,那么我们在Fragment中使用addToBackStack()方法。我们来理解一下
案例1:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, fragment, "TAG")
.addToBackStack("TAG")
.commit();
案例2:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, fragment, "TAG")
.commit();
FragmentManger的添加和替换功能可以这样描述
1. 添加意味着它会将片段添加到片段返回堆栈中,并在您提供的给定帧中显示
就像
getFragmentManager.beginTransaction.add(R.id.contentframe,Fragment1.newInstance(),null)
2.替换意味着你在给定的帧中用另一个片段替换这个片段
getFragmentManager.beginTransaction.replace(R.id.contentframe,Fragment1.newInstance(),null)
两者之间的主要实用程序是,当你回堆叠时,replace将刷新片段,而add将不会刷新之前的片段。
add和replace之间一个更重要的区别是:
Replace删除现有的片段并添加一个新的片段。这意味着当你按下返回按钮时,被替换的片段将被创建,它的onCreateView被调用。而add保留现有的片段并添加一个新的片段,这意味着现有的片段将是活动的,它们不会处于“暂停”状态,因此当按下后退按钮时,createview不会为现有的片段(在添加新片段之前的片段)调用。
就片段的生命周期事件而言,onPause, onResume, onCreateView和其他生命周期事件将在替换的情况下被调用,但在添加的情况下不会被调用。
Edit: One should be careful if she is using some kind of event bus library like Greenrobot's Eventbus and reusing the same fragment to stack the fragment on top of other via add. In this scenario, even though you follow the best practice and register the event bus in onResume and unregister in onPause, event bus would still be active in each instance of the added fragment as add fragment wont call either of these fragment life cycle methods. As a result event bus listener in each active instance of the fragment would process the same event which may not be what you want.