Android 困境:何时使用片段与活动:

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20306091/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:37:09  来源:igfitidea点击:

Dilemma: when to use Fragments vs Activities:

androidandroid-fragmentsandroid-activityarchitecture

提问by Emil Adz

I know that Activitiesare designed to represent a single screen of my application, while Fragmentsare designed to be reusable UI layouts with logic embedded inside of them.

我知道它Activities旨在代表我的应用程序的单个屏幕,而Fragments被设计为可重用的 UI 布局,其中嵌入了逻辑。

Until not long ago, I developed an application as it said that they should be developed. I created an Activityto represent a screen of my application and used Fragments for ViewPageror Google Maps. I rarely created a ListFragmentor other UI that can be reused several times.

直到不久前,我开发了一个应用程序,因为它说应该开发它们。我创建了一个Activity来代表我的应用程序的屏幕并使用 Fragments for ViewPageror Google Maps。我很少创建一个ListFragment或其他可以重复使用多次的 UI。

Recently I stumbled on a project that contains only 2 Activitiesone is a SettingsActivityand other one is the MainActivity. The layout of the MainActivityis populated with many hidden full screen UI fragments and only one is shown. In the Activitylogic there are many FragmentTransitionsbetween the different screens of the application.

最近我偶然发现了一个项目,其中只包含 2 个,Activities一个是 a SettingsActivity,另一个是MainActivity. 的布局MainActivity填充了许多隐藏的全屏 UI 片段,并且只显示了一个。在应用程序的不同屏幕之间Activity有很多逻辑FragmentTransitions

What I liked about this approach is that because the application uses an ActionBar, it stays intact and does not move with the screen switching animation, which is what happens with Activityswitching. This give a more fluent feel to those screen transitions.

我喜欢这种方法的一点是,因为应用程序使用了ActionBar,所以它保持完整并且不会随着屏幕切换动画而移动,这就是Activity切换时发生的情况。这为这些屏幕转换提供了更流畅的感觉。

So I guess what I'm asking is to share your current development manner regarding this topic, I know it might look like an opinion based question at first look but I look at it as an Android design and architecture question... Not really an opinion based one.

所以我想我要问的是分享您当前关于这个主题的开发方式,我知道它乍一看可能看起来像一个基于意见的问题,但我将其视为一个 Android 设计和架构问题......并不是一个真正的问题基于意见的。

UPDATE (01.05.2014):Following this presentation by Eric Burkefrom Square, (which I have to say is a great presentation with a lot of useful tools for android developers. And I am not related in any way to Square)

UPDATE(2014年5月1日):在此之后呈现由埃里克·伯克广场,(这是我不得不说是一个有很多的Android开发人员有用的工具,一个伟大的演示和我没有以任何方式广场相关)

http://www.infoq.com/presentations/Android-Design/

http://www.infoq.com/presentations/Android-Design/

From my personal experience over the past few months, I found that the best way to construct my applications is to create groups of fragments that come to represent a flowin the application and present all those fragments in one Activity. So basically you will have the same number of Activitiesin your application as the number of flows. That way the action bar stays intact on all the flow's screens, but is being recreated on changing a flow which makes a lot of sense. As Eric Burke states and as I have come to realize as well, the philosophy of using as few Activitiesas possible is not applicable for all situations because it creates a mess in what he calls the "God" activity.

根据我过去几个月的个人经验,我发现构建我的应用程序的最佳方法是创建一组片段,这些片段代表应用程序中的一个,并将所有这些片段呈现在一个Activity. 所以基本上你Activities的应用程序中的数量与流的数量相同。这样,操作栏在所有流程的屏幕上都保持不变,但会在更改流程时重新创建,这很有意义。正如埃里克·伯克 (Eric Burke) 所说,并且我也逐渐意识到,尽可能少使用的哲学Activities并不适用于所有情况,因为它会在他所谓的“上帝”活动中造成混乱。

回答by sandalone

Experts will tell you: "When I see the UI, I will know whether to use an Activityor a Fragment". In the beginning this will not have any sense, but in time, you will actually be able to tell if you need Fragmentor not.

专家会告诉你:“当我看到UI时,我就会知道是使用anActivity还是a Fragment”。一开始这没有任何意义,但随着时间的推移,您实际上将能够判断您是否需要Fragment

There is a good practice I found very helpful for me. It occurred to me while I was trying to explain something to my daughter.

我发现有一个很好的做法对我很有帮助。当我试图向我的女儿解释一些事情时,我突然想到了这一点。

Namely, imagine a box which represents a screen. Can you load another screen in this box? If you use a new box, will you have to copy multiple items from the 1st box? If the answer is Yes, then you should use Fragments, because the root Activitycan hold all duplicated elements to save you time in creating them, and you can simply replace parts of the box.

即,想象一个代表屏幕的框。你能在这个盒子里加载另一个屏幕吗?如果您使用新盒子,您是否需要从第一个盒子中复制多个项目?如果答案是肯定的,那么您应该使用Fragments,因为根Activity可以保存所有重复的元素以节省创建它们的时间,并且您可以简单地替换框的部分。

But don't forgetthat you always need a box container (Activity) or your parts will be dispersed. So one box with parts inside.

不要忘记,您总是需要一个盒子容器 ( Activity),否则您的零件会散落一地。所以一个盒子里面有零件。

Take care not to misuse the box. Android UX experts advise (you can find them on YouTube) when we should explicitly load another Activity, instead to use a Fragment(like when we deal with the Navigation Drawer which has categories). Once you feel comfortable with Fragments, you can watch all their videos. Even more they are mandatory material.

注意不要误用盒子。Android UX 专家建议(您可以在 YouTube 上找到它们)何时应该显式加载另一个Activity,而不是使用 a Fragment(例如当我们处理具有类别的导航抽屉时)。一旦您感到满意Fragments,您就可以观看他们的所有视频。更重要的是,它们是强制性材料。

Can you right now look at your UI and figure out if you need an Activityor a Fragment? Did you get a new perspective? I think you did.

你现在可以看看你的 UI 并弄清楚你是否需要 anActivity或 aFragment吗?你有没有获得新的视角?我想你做到了。

回答by VJ Vélan Solutions

My philosophy is this:

我的哲学是这样的:

Create an activity only if it's absolutely absolutely required. With the back stack made available for committing bunch of fragment transactions, I try to create as few activities in my app as possible. Also, communicating between various fragments is much easier than sending data back and forth between activities.

仅在绝对需要时才创建活动。后堆栈可用于提交一堆片段事务,我尝试在我的应用程序中创建尽可能少的活动。此外,各个片段之间的通信比在活动之间来回发送数据要容易得多。

Activity transitions are expensive, right? At least I believe so - since the old activity has to be destroyed/paused/stopped, pushed onto the stack, and then the new activity has to be created/started/resumed.

活动转换很昂贵,对吧?至少我相信 - 因为旧活动必须被销毁/暂停/停止,推送到堆栈上,然后新活动必须被创建/启动/恢复。

It's just my philosophy since fragments were introduced.

自从引入片段以来,这只是我的哲学。

回答by android developer

Well, according to Google's lectures (maybe here, I don't remember) , you should consider using Fragments whenever it's possible, as it makes your code easier to maintain and control.

好吧,根据 Google 的讲座(也许在这里,我不记得了),您应该尽可能考虑使用 Fragments,因为它使您的代码更易于维护和控制。

However, I think that on some cases it can get too complex, as the activity that hosts the fragments need to navigate/communicate between them.

但是,我认为在某些情况下它会变得过于复杂,因为承载片段的活动需要在它们之间导航/通信。

I think you should decide by yourself what's best for you. It's usually not that hard to convert an activity to a fragment and vice versa.

我认为你应该自己决定什么最适合你。将活动转换为片段通常并不难,反之亦然。

I've created a post about this dillema here, if you wish to read some further.

我创建了一个关于这个dillema后在这里,如果你想读一些进一步。

回答by Qylin

Why I prefer Fragment over Activity in ALL CASES.

为什么在所有情况下我都更喜欢 Fragment 而不是 Activity。

  • Activity is expensive. In Fragment, views and property states are separated - whenever a fragment is in backstack, its views will be destroyed. So you can stack much more Fragments than Activity.

  • Backstackmanipulation. With FragmentManager, it's easy to clear all the Fragments, insert more than on Fragments and etcs. But for Activity, it will be a nightmare to manipulate those stuff.

  • A much predictable lifecycle. As long as the host Activity is not recycled. the Fragments in the backstack will not be recycled. So it's possible to use FragmentManager::getFragments()to find specific Fragment (not encouraged).

  • 活动很贵。在 Fragment 中,视图和属性状态是分开的——只要一个片段在 中backstack,它的视图就会被销毁。因此,您可以堆叠比 Activity 多得多的 Fragment。

  • Backstack操纵。使用FragmentManager,可以轻松清除所有 Fragment,插入比 Fragment 等更多的内容。但是对于 Activity 来说,操纵这些东西将是一场噩梦。

  • 一个非常可预测的生命周期。只要宿主Activity不被回收。backstack 中的 Fragments 不会被回收。所以可以用来FragmentManager::getFragments()查找特定的 Fragment(不鼓励)。

回答by Francis

Since Jetpack, Single-Activity appis the preferred architecture. Usefull especially with the Navigation Architecture Component.

Jetpack以来,Single-Activity 应用程序是首选架构。尤其适用于导航架构组件

source

来源

回答by Isaac Urbina

In my opinion it's not really relevant. The key factor to consider is

在我看来,这并不重要。要考虑的关键因素是

  1. how often are you gonna reuse parts of the UI (menus for example),
  2. is the app also for tablets?
  1. 你多久会重复使用 UI 的一部分(例如菜单),
  2. 该应用程序也适用于平板电脑吗?

The main use of fragments is to build multipane activities, which makes it perfect for Tablet/Phone responsive apps.

片段的主要用途是构建多窗格活动,这使其非常适合平板电脑/手机响应式应用程序。

回答by guest

Don't forget that an activity is application's block/component which can be shared and started through Intent! So each activity in your application should solve only one kind of task. If you have only one task in your application then I think you need only one activity and many fragments if needed. Of course you can reuse fragments in future activities which solve another tasks. This approach will be clear and logical separation of tasks. And you no need to maintain one activity with different intent filter parameters for different sets of fragments. You define tasks at the design stage of the development process based on requirements.

不要忘记活动是应用程序的块/组件,可以通过 Intent 共享和启动!所以你的应用程序中的每个活动应该只解决一种任务。如果您的应用程序中只有一项任务,那么我认为您只需要一项活动和许多片段(如果需要)。当然,您可以在将来解决其他任务的活动中重用片段。这种方法将任务进行清晰和合乎逻辑的分离。并且您无需为不同的片段集维护一个具有不同意图过滤器参数的活动。您可以在开发过程的设计阶段根据需求定义任务。

回答by TheHebrewHammer

There's more to this than you realize, you have to remember than an activity that is launched does not implicitly destroy the calling activity. Sure, you can set it up such that your user clicks a button to go to a page, you start that page's activity and destroy the current one. This causes a lot of overhead. The best guide I can give you is:

这比您意识到的要多,您必须记住,启动的活动不会隐式地破坏调用活动。当然,您可以设置它,让您的用户单击一个按钮转到一个页面,您启动该页面的活动并销毁当前的活动。这会导致大量开销。我能给你的最好的指南是:

** Start a new activity only if it makes sense to have the main activity and this one open at the same time (think of multiple windows).

** 仅当主活动和此活动同时打开有意义时才启动新活动(考虑多个窗口)。

A great example of when it makes sense to have multiple activities is Google Drive. The main activity provides a file explorer. When a file is opened, a new activity is launched to view that file. You can press the recent apps button which will allow you to go back to the browser without closing the opened document, then perhaps even open another document in parallel to the first.

Google Drive 是一个很好的例子,说明什么时候有多个活动是有意义的。主要活动提供了一个文件浏览器。打开文件时,会启动一个新活动来查看该文件。您可以按最近使用的应用程序按钮,这将允许您在不关闭打开的文档的情况下返回浏览器,然后甚至可以在第一个文档的同时打开另一个文档。

回答by I Love Coding

Thing I did: Using less fragment when possible. Unfortunately, it's possible in almost case. So, I end up with a lot of fragments and a little of activities. Some drawbacks I've realized:

我所做的:尽可能使用更少的片段。不幸的是,这几乎是可能的。所以,我最终得到了很多片段和一些活动。我意识到的一些缺点:

  • ActionBar& Menu: When 2 fragment has different title, menu, that
    will hard to handle. Ex: when adding new fragment, you can change action bar title, but when pop it from backstackthere is no way to restore the old title. You may need an Toolbar in every fragment for this case, but let believe me, that will spend you more time.
  • When we need startForResult, activity has but fragment hasn't.
  • Don't have transition animation by default
  • ActionBar& 菜单:当 2 个片段具有不同的标题、菜单时,
    将难以处理。例如:添加新片段时,您可以更改操作栏标题,但是弹出时backstack无法恢复旧标题。对于这种情况,您可能需要在每个片段中都有一个工具栏,但相信我,这会花费您更多的时间。
  • 当我们需要时startForResult,活动有但片段没有。
  • 默认没有过渡动画

My solution for this is using an Activity to wrapa fragment inside. So we have separate action bar, menu, startActivityForResult, animation,...

我对此的解决方案是使用 Activity片段包装在里面。所以我们有单独的操作栏、菜单startActivityForResult、动画、...

回答by Sanchit Bhasin

The one big advantage of a fragmentover activity is that , the code which is used for fragment can be used for different activities.so, it provides re-usabilityof code in application development.

fragmentover Activity的一大优点是,用于片段的代码可以用于不同的活动。因此,它在应用程序开发中提供了代码的可重用性