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

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

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

我的问题是关于片段的:

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

奖金问题:

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


当前回答

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

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

其他回答

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

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

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

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

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

片段在某些情况下特别有用,比如我们想在所有页面中保留一个导航抽屉。你可以用你想要的任何片段来膨胀框架布局,并且仍然可以访问导航抽屉。

如果您使用了一个活动,那么您将不得不在所有活动中保留抽屉,这将导致冗余代码。这是片段的一个有趣用法。

我是Android的新手,仍然认为碎片是有帮助的。

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

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

片段是应用程序的用户界面或行为的一部分,可以放在活动中,从而实现更模块化的活动设计。如果我们说片段是一种子活动,那也不会错。

以下是关于片段的要点:

A fragment has its own layout and its own behavior with its own lifecycle callbacks. You can add or remove fragments in an activity while the activity is running. You can combine multiple fragments in a single activity to build a multi-pane UI. A fragment can be used in multiple activities. The fragment life cycle is closely related to the lifecycle of its host activity. When the activity is paused, all the fragments available in the acivity will also be stopped. A fragment can implement a behavior that has no user interface component. Fragments were added to the Android API in Android 3 (Honeycomb) with API version 11.

欲了解更多详情,请访问官方网站碎片。