1.Each FragmentTransaction should use setReorderingAllowed(true),特别是对于行为兼容性,默认情况下不启用重新排序标志。但是,需要允许FragmentManager正确执行您的FragmentTransaction,特别是当它在后堆栈上操作并运行动画和转换时。启用该标志可确保如果同时执行多个事务,则任何中间片段(即添加后立即替换的片段)都不会经历生命周期更改,也不会执行其动画或转换。请注意,此标志影响事务的初始执行和使用popBackStack()反转事务。

2.强烈推荐FragmentVontainerView作为fragment的容器

3.Strongly recommended to always use fragment operations that take a Class rather than a fragment instance to ensure that the same mechanisms for creating the fragment are also fro restoring the fragment from a saved.

4.Commit is asynchronous(非共时的),Calling commit() doesn't perform the transaction immediately.Rather,the transaction is scheduled(安排) to run on the main UI thread as soon as it is able to do so.If necessary,however,you can call commitNow() to run the fragment transaction on your UI thread immediately.

        Note that commitNow is incompatible(不兼容) with addToBackStake.或者,可以通过调用executePendingTransactions()来执行由commit()调用提交的所有尚未运行的挂起碎片事务。此方法与addToBackStack兼容。

5.operation ordering is significat(很重要).particularly when using setCustomAnimations().This method applies(应用) the given animations(动画) to all fragment operations that follow it

supportFragmentManager.commit {
    setCustomAnimations(enter1, exit1, popEnter1, popExit1)
    add<ExampleFragment>(R.id.container) // gets the first animations
    setCustomAnimations(enter2, exit2, popEnter2, popExit2)
    add<ExampleFragment>(R.id.container) // gets the second animations
}

6.FragmentTransactions会影响事务范围内添加的各个片段的生命周期状态。创建FragmentTransaction时,setMaxLifecycle()为给定片段设置最大状态。例如,ViewPager2使用setMaxLifecycle()将屏幕外片段限制为启动状态。

7.Use the FragmentTransaction methods show() and hide() to show and hide the view of fragments that have been added to a container.These methods set the visiblity of the fragment's views without affecting the lifecycle of the fragment

8.FragmentTransaction方法detach()将片段与UI分离,从而破坏其视图层次结构。片段保持与放在后堆栈上时相同的状态(停止)。这意味着该片段已从UI中删除,但仍由片段管理器管理。attach()方法重新附着以前从中分离的片段。这将导致其视图层次结构被重新创建、附加到UI并显示。

9.由于FragmentTransaction被视为单个原子操作集,因此在同一事务中对同一个片段实例进行分离和附加的调用可以有效地相互抵消,从而避免破坏和立即重新创建片段的UI。如果要分离然后立即重新附加片段,请使用单独的事务,如果使用commit(),则由executePendingOperations()分隔。(note:The attach() and detach() methods are not related to the Fragment methods of onAttach() and onDetach().)

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐