什么是FragmentTransaction
如果你尝试过动态添加碎片,一定使用过类似于以下的代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 加载主界面的碎片
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment, new MyFragment());
// 或者这样
//transaction.replace(R.id.fragment, new MyFragment())
transaction.commit();
}
}
FragmentTransaction允许你在与这个FragmentManager关联的Fragment上启动一系列编辑操作。
简短的来说,add方法添加碎片不会移除已经添加的碎片。但是replace会先清除所有碎片然后才添加新的碎片
Add
该方法有很多重载,贴出两个展示
public FragmentTransaction add (int containerViewId, Fragment fragment);
public FragmentTransaction add (int containerViewId, Fragment fragment, String tag);
containerViewId指定显示该Fragment的容器,而tag可以为添加的碎片指定一个标记,一种作用是通过FragmentManager
的findFragmentByTag(String tag)
方法可以找到这个碎片。
添加一个fragment与往活动栈添加一个activity类似,add()
并不会清空前一个添加的fragment。
注意事项
- 不允许添加同一个fragment实例。
- 添加进来的fragment都是可见的,后添加的fragment会展示在先添加的fragment上面,在绘制界面的时候会绘制所有可见的view。这会造成混乱,所以
add
一般会配合hide
方法或者remove
方法使用。
hide
public FragmentTransaction hide (Fragment fragment);
Hides an existing fragment. This is only relevant for fragments whose views have been added to a container, as this will cause the view to be hidden.
(隐藏现有碎片。这只与视图已添加到容器中的碎片相关,因为这将导致视图被隐藏。)
remove
public FragmentTransaction remove (Fragment fragment);
Remove an existing fragment. If it was added to a container, its view is also removed from that container.
(移除一个现有碎片。如果它已添加到容器,那么它的视图一样会从容器移除)
以下是使用的简短示例:
transaction.add(R.id.fragment_container, oneFragment).hide(twoFragment).commit();
Replace
public FragmentTransaction replace (int containerViewId, Fragment fragment);
public FragmentTransaction replace (int containerViewId, Fragment fragment, String tag);
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment)
for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String)
with the same arguments given here.
(替换已添加到容器中的现有碎片。这与为所有当前添加的碎片调用remove(Fragment)基本相同,这些片段使用相同的containerViewId添加,然后使用此处给定的相同参数调用add(int,Fragment,String))