在Android API 11+中,谷歌发布了一个名为Fragment的新类。

在视频中,谷歌建议,只要可能(link1, link2),我们应该使用片段而不是活动,但他们没有解释确切的原因。

片段的目的是什么以及它们的一些可能的用途(除了一些可以通过简单的视图/布局轻松实现的UI示例)?

我的问题是关于片段的:

使用片段的目的是什么? 与使用活动/视图/布局相比,使用片段的优点和缺点是什么?

奖金问题:

您能否为片段提供一些真正有趣的用途?谷歌在他们的视频里没有提到的事情? 在片段和包含它们的活动之间进行通信的最佳方式是什么? 当你使用片段时,最重要的事情是什么?从你的经验中有什么建议和警告吗?


当前回答

我知道这个问题已经讨论得很激烈了,但我想再补充几点:

Frags can be used to populate Menus and can handle MenuItem clicks on their own. Thus giving futher modulation options for your Activities. You can do ContextualActionBar stuff and so on without your Activity knowing about it and can basically decouple it from the basic stuff your Activity handles (Navigation/Settings/About). A parent Frag with child Frags can give you further options to modulize your components. E.g. you can easily swap Frags around, put new Frags inside a Pager or remove them, rearrange them. All without your Activity knowing anything about it just focusing on the higher level stuff.

其他回答

这是我在片段中发现的重要信息:

Historically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. Instead the object must be serialized or a globally accessible reference made available. By making each screen a separate Fragment, this data passing headache is completely avoided. Fragments always exist within the context of a given Activity and can always access that Activity. By storing the information of interest within the Activity, the Fragment for each screen can simply access the object reference through the Activity.

来源:https://www.pluralsight.com/blog/software-development/android-fragments

如果你以前写过前端,那么使用前端组件(React, Vue或Angular)。将片段视为活动中的可重用组件。

我知道这个问题已经讨论得很激烈了,但我想再补充几点:

Frags can be used to populate Menus and can handle MenuItem clicks on their own. Thus giving futher modulation options for your Activities. You can do ContextualActionBar stuff and so on without your Activity knowing about it and can basically decouple it from the basic stuff your Activity handles (Navigation/Settings/About). A parent Frag with child Frags can give you further options to modulize your components. E.g. you can easily swap Frags around, put new Frags inside a Pager or remove them, rearrange them. All without your Activity knowing anything about it just focusing on the higher level stuff.

1.使用片段的目的是什么?

答: 处理器件形状因子差异。 在应用程序屏幕之间传递信息。 用户界面组织。 高级UI隐喻。

Fragments存在于活动中,并具有:

它自己的生命周期 自己的布局 它自己的子片段等等。

将Fragments视为它所属的主活动的子活动,它不能单独存在,它可以一次又一次地被调用/重用。希望这对你有所帮助。