Android 为什么使用片段,何时使用片段而不是活动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10478233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why fragments, and when to use fragments instead of activities?
提问by android developer
In Android API 11+, Google has released a new class called Fragment
.
在 Android API 11+ 中,Google 发布了一个名为Fragment
.
In the videos, Google suggests that whenever possible (link1, link2), we should use fragments instead of activities, but they didn't explain exactly why.
在视频中,Google 建议在可能的情况下(link1、link2),我们应该使用片段而不是活动,但他们没有确切解释原因。
What's the purpose of fragments and some possible uses of them (other than some UI examples that can be easily be achieved by simple views/layouts)?
片段的目的是什么以及它们的一些可能用途(除了一些可以通过简单视图/布局轻松实现的 UI 示例)?
My question is about fragments:
我的问题是关于片段:
- What are the purposes of using a fragment?
- What are the advantages and disadvantages of using fragments compared to using activities/views/layouts?
- 使用片段的目的是什么?
- 与使用活动/视图/布局相比,使用片段的优缺点是什么?
Bonus questions:
奖金问题:
- Can you give some really interesting uses for fragments? Things that Google didn't mention in their videos?
- What's the best way to communicate between fragments and the activities that contain them?
- What are the most important things to remember when you use fragments? Any tips and warnings from your experience?
- 你能给片段提供一些非常有趣的用途吗?谷歌在他们的视频中没有提到的事情?
- 在片段和包含它们的活动之间进行通信的最佳方式是什么?
- 使用片段时要记住的最重要的事情是什么?您的经验有什么提示和警告吗?
采纳答案by Glenn Bech
#1 & #2 what are the purposes of using a fragment & what are the advantages and disadvantages of using fragments compared to using activities/views/layouts?
#1 & #2 使用片段的目的是什么?与使用活动/视图/布局相比,使用片段的优缺点是什么?
Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;
Fragment 是 Android 创建可重用用户界面的解决方案。您可以使用活动和布局(例如使用包含)来实现一些相同的事情。然而; 片段被连接到 Android API,来自 HoneyComb 等。让我详细说明;
The
ActionBar
. If you want tabs up there to navigate your app, you quickly see thatActionBar.TabListener
interface gives you aFragmentTransaction
as an input argument to theonTabSelected
method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.The
FragmentManager
handles ?back? for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.You can use the cool
ViewPager
with aFragmentPagerAdapter
to create swipe interfaces. TheFragmentPagerAdapter
code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.
You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use
ActionBarSherlock
and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like theActionBar
, with tabs, overflow, split action bar, viewpager etc.
的
ActionBar
。如果您希望在那里使用选项卡来导航您的应用程序,您很快就会看到该ActionBar.TabListener
界面为您提供了一个FragmentTransaction
作为该onTabSelected
方法的输入参数。您可能会忽略这一点,并做一些其他聪明的事情,但是您将针对 API 工作,而不是使用它。该
FragmentManager
手柄?回来?以非常聪明的方式为您服务。返回并不意味着回到上一个活动,就像常规活动一样。这意味着回到之前的片段状态。您可以使用
ViewPager
带有 a的酷FragmentPagerAdapter
来创建滑动界面。该FragmentPagerAdapter
代码是比普通的适配器更清洁,它控制各个片段的实例。如果您在尝试为手机和平板电脑创建应用程序时使用 Fragments,您的生活会轻松很多。由于这些片段与 Honeycomb+ API 紧密相连,因此您也希望在手机上使用它们来重用代码。这就是兼容性库派上用场的地方。
您甚至可以并且应该将片段用于仅适用于手机的应用程序。如果您考虑便携性。我使用
ActionBarSherlock
和兼容性库来创建“ICS 外观”应用程序,这些应用程序从 1.6 版开始看起来都一样。您可以获得最新的功能,例如ActionBar
带有选项卡、溢出、拆分操作栏、viewpager 等。
Bonus 2
奖金 2
The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity()
with data on it. The intent is passed on to all fragments of the activity you launch.
在片段之间进行通信的最佳方式是意图。当您按下 Fragment 中的某些内容时,您通常会调用StartActivity()
其上的数据。意图被传递到您启动的活动的所有片段。
回答by Nikolay Elenkov
Not sure what video(s) you are referring to, but I doubt they are saying you should use fragments instead of activities, because they are not directly interchangeable. There is actually a fairly detailed entryin the Dev Guide, consider reading it for details.
不确定您指的是什么视频,但我怀疑他们是说您应该使用片段而不是活动,因为它们不能直接互换。Dev Guide 中实际上有一个相当详细的条目,请考虑阅读它以获取详细信息。
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.
简而言之,片段存在于活动中,每个活动可以承载许多片段。与活动一样,它们具有特定的生命周期,与活动不同,它们不是顶级应用程序组件。片段的优点包括代码重用和模块化(例如,在许多活动中使用相同的列表视图),包括构建多窗格界面的能力(主要在平板电脑上有用)。主要缺点是(一些)增加了复杂性。您通常可以以非标准且不太稳健的方式使用(自定义)视图实现相同的目的。
回答by mani
A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity which enable a more modular activity design. It will not be wrong if we say a fragment is a kind of subactivity.
Fragment 是应用程序的用户界面或行为的一部分,可以放置在 Activity 中,从而实现更加模块化的 Activity 设计。如果我们说一个片段是一种子活动,这并没有错。
Following are important points about a fragment:
以下是关于片段的要点:
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.
片段有自己的布局和自己的行为以及自己的生命周期回调。
您可以在活动运行时在活动中添加或删除片段。
您可以在单个活动中组合多个片段以构建多窗格 UI。
一个片段可以用于多个活动。
片段生命周期与其宿主活动的生命周期密切相关。
当活动暂停时,活动中所有可用的片段也将停止。
片段可以实现没有用户界面组件的行为。
在API 版本 11 的Android 3(Honeycomb) 中,片段被添加到 Android API 中。
For more details, please visit the official site, Fragments.
有关更多详细信息,请访问官方网站Fragments。
回答by Kaveesh Kanwal
This is important information that I found on 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.
过去,Android 应用程序中的每个屏幕都是作为一个单独的 Activity 实现的。这给在屏幕之间传递信息带来了挑战,因为 Android Intent 机制不允许在活动之间直接传递引用类型(即对象)。相反,对象必须被序列化或提供一个全局可访问的引用。
通过使每个屏幕成为一个单独的 Fragment,完全避免了这种令人头疼的数据传递问题。片段始终存在于给定 Activity 的上下文中,并且始终可以访问该 Activity。通过在 Activity 中存储感兴趣的信息,每个屏幕的 Fragment 可以通过 Activity 简单地访问对象引用。
Source: https://www.pluralsight.com/blog/software-development/android-fragments
来源:https: //www.pluralsight.com/blog/software-development/android-fragments
回答by Chandrima Bhattacharjee
Activities are the full screen components in the app with the toolbar, everything else are preferably Fragments. One full screen parent activity with a toolbar can have multiple panes, scrollable pages, dialogs, etc. (all fragments), all of which can be accessed from the parent and communicate via the parent.
活动是应用程序中带有工具栏的全屏组件,其他一切最好是片段。一个带有工具栏的全屏父 Activity 可以有多个窗格、可滚动页面、对话框等(所有片段),所有这些都可以从父级访问并通过父级进行通信。
Example:
例子:
Activity A, Activity B, Activity C:
活动 A、活动 B、活动 C:
- All activities need to have same code repeated, to show a basic toolbar for example, or inherit from a parent activity (becomes cumbersome to manage).
- To move from one activity to the other, either all of them need to be in memory (overhead) or one needs to be destroyed for the other to open.
- Communication between activities can be done via Intents.
- 所有活动都需要重复相同的代码,例如显示一个基本的工具栏,或者从父活动继承(变得难以管理)。
- 要从一个活动转移到另一个活动,要么所有这些活动都需要在内存中(开销),要么需要销毁一个活动才能打开另一个活动。
- 活动之间的通信可以通过意图完成。
vs
对比
Activity A, Fragment 1, Fragment 2, Fragment 3:
活动 A,片段 1,片段 2,片段 3:
- No code repetition, all screens have toolbars etc. from that one activity.
- Several ways to move from one fragment to next - view pager, multi pane etc.
- Activity has most data, so minimal inter-fragment communication needed. If still necessary, can be done via interfaces easily.
- Fragments do not need to be full screen, lots of flexibility in designing them.
- Fragments do not need to inflate layout if views are not necessary.
- Several activities can use the same fragment.
- 没有代码重复,所有屏幕都有来自该活动的工具栏等。
- 从一个片段移动到下一个片段的几种方法 - 查看寻呼机、多窗格等。
- 活动拥有最多的数据,因此需要最少的片段间通信。如果仍然需要,可以通过接口轻松完成。
- Fragments 不需要是全屏的,设计它们有很大的灵活性。
- 如果不需要视图,片段不需要膨胀布局。
- 多个活动可以使用同一个片段。
回答by Nithin Baby
Fragments are of particular use in some cases like where we want to keep a navigation drawer in all our pages. You can inflate a frame layout with whatever fragment you want and still have access to the navigation drawer.
片段在某些情况下特别有用,例如我们希望在所有页面中保留导航抽屉。您可以使用您想要的任何片段来扩展框架布局,并且仍然可以访问导航抽屉。
If you had used an activity, you would have had to keep the drawer in all activities which makes for redundant code. This is one interesting use of a fragment.
如果您使用了一个活动,您将不得不在所有活动中保留抽屉,这会产生冗余代码。这是片段的一种有趣用法。
I'm new to Android and still think a fragment is helpful this way.
我是 Android 新手,仍然认为片段在这方面很有帮助。
回答by einschnaehkeee
I know this was already discussed to death, but I'd like to add some more points:
我知道这已经被讨论到死,但我想补充几点:
Frags can be used to populate
Menu
s and can handleMenuItem
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.
Frags 可用于填充
Menu
s 并可以MenuItem
自行处理点击。从而为您的活动提供更多调制选项。您可以在 Activity 不知道的情况下执行 ContextualActionBar 等操作,并且基本上可以将其与您的 Activity 处理的基本内容(导航/设置/关于)分离。带有子 Frag 的父 Frag 可以为您提供更多选项来模块化您的组件。例如,您可以轻松地交换 Frags,将新 Frags 放入 Pager 中或移除它们,重新排列它们。所有这些都不需要您的 Activity 对其一无所知,而只是专注于更高级别的东西。
回答by superkytoz
A fragment lives inside an activity, while an activity lives by itself.
片段存在于活动中,而活动本身存在。
回答by maniix
Fragments lives within the Activity and has:
Fragments 存在于 Activity 中,并且具有:
- its own lifecycle
- its own layout
- its own child fragments and etc.
- 它自己的生命周期
- 自己的布局
- 它自己的子片段等。
Think of Fragments as a sub activity of the main activity it belongs to, it cannot exist of its own and it can be called/reused again and again. Hope this helps :)
将 Fragments 视为它所属的主要活动的子活动,它不能单独存在并且可以一次又一次地调用/重用。希望这可以帮助 :)
回答by Prithiv Dharmaraj
1.Purposes of using a fragment?
1.使用fragment的目的?
- Ans:
- Dealing with device form-factor differences.
- Passing information between app screens.
- User interface organization.
- Advanced UI metaphors.
- 答:
- 处理设备外形差异。
- 在应用程序屏幕之间传递信息。
- 用户界面组织。
- 高级 UI 隐喻。