在Android API 11+中,谷歌发布了一个名为Fragment的新类。
在视频中,谷歌建议,只要可能(link1, link2),我们应该使用片段而不是活动,但他们没有解释确切的原因。
片段的目的是什么以及它们的一些可能的用途(除了一些可以通过简单的视图/布局轻松实现的UI示例)?
我的问题是关于片段的:
使用片段的目的是什么?
与使用活动/视图/布局相比,使用片段的优点和缺点是什么?
奖金问题:
您能否为片段提供一些真正有趣的用途?谷歌在他们的视频里没有提到的事情?
在片段和包含它们的活动之间进行通信的最佳方式是什么?
当你使用片段时,最重要的事情是什么?从你的经验中有什么建议和警告吗?
片段可以被认为是ui元素复合树中的非根组件,而活动位于复合树(ui树)的顶部。
A rule of thumb on when not to use Fragment is when as a child the fragment has a conflicting attribute, e.g., it may be immersive or may be using a different style all together or has some other architectural / logical difference and doesn't fit in the existing tree homogeneously.
A rule of thumb on when to prefer Activity over Fragment is when the task (or set of coherent task) is fully independent and reusable and does some heavy weight lifting and should not be burdened further to conform to another parent-child composite (SRP violation, second responsibility would be to conform to the composite). For e.g., a MediaCaptureActivity that captures audio, video, photos etc and allows for edits, noise removal, annotations on photos etc and so on. This activity/module may have child fragments that do more granular work and conform to a common display theme.
片段可以被认为是ui元素复合树中的非根组件,而活动位于复合树(ui树)的顶部。
A rule of thumb on when not to use Fragment is when as a child the fragment has a conflicting attribute, e.g., it may be immersive or may be using a different style all together or has some other architectural / logical difference and doesn't fit in the existing tree homogeneously.
A rule of thumb on when to prefer Activity over Fragment is when the task (or set of coherent task) is fully independent and reusable and does some heavy weight lifting and should not be burdened further to conform to another parent-child composite (SRP violation, second responsibility would be to conform to the composite). For e.g., a MediaCaptureActivity that captures audio, video, photos etc and allows for edits, noise removal, annotations on photos etc and so on. This activity/module may have child fragments that do more granular work and conform to a common display theme.
不确定你指的是什么视频,但我怀疑他们说你应该使用片段而不是活动,因为它们不能直接互换。实际上,在开发指南中有一个相当详细的条目,考虑阅读它的详细信息。
In short, fragments live inside activities, and each activity can host many fragments. Like activities, they have a specific lifecycle, unlike activities, they are not top-level application components. Advantages of fragments include code reuse and modularity (e.g., using the same list view in many activities), including the ability to build multi-pane interfaces (mostly useful on tablets). The main disadvantage is (some) added complexity. You can generally achieve the same thing with (custom) views in a non-standard and less robust way.