Android 有多少活动与片段?

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

How many Activities vs Fragments?

androidandroid-fragmentsandroid-listfragment

提问by Richard Le Mesurier

Intro:

介绍:

The basic "Fragments Tutorial" pattern goes something like this:

基本的“片段教程”模式是这样的:

  1. On a tablet, have a list on the left, details on the right.
  2. Both are Fragmentsand both reside in the same Activity.
  3. On a phone, have a list Fragmentin one Activity.
  4. Launch a new Activitywith the details Fragment.
  1. 在平板电脑上,左侧有列表,右侧有详细信息。
  2. 两者都是 Fragments并且都驻留在同一个Activity.
  3. 在电话上,将清单Fragment合二为一Activity
  4. 推出新Activity的细节Fragment

(e.g. Android 3.0 Fragments API by Dianne Hackbornand the Fragments API Guide)

(例如Dianne Hackborn 的 Android 3.0 Fragments APIFragments API 指南

On both devices, functionality is in the Fragments. (simple)

在这两种设备上,功能都在Fragments. (简单的)

On the Tablet, the whole app is 1 Activity, on the phone, there are many Activities.

平板上,整个app是1个Activity,在手机上,有很多Activities



Questions:

问题:

  • Is there a reason to split the phone app into many Activities?
  • 是否有理由将手机应用拆分为多个Activities

One problemwith this method, is that you duplicate a lot of the logicin the main Tablet Activity, and in the separate Phone Activities.

这种方法的一个问题是,您在主 Tablet和单独的 Phone 中复制了很多逻辑ActivityActivities

  • Would it not be easier to retain the 1 Activity model in both cases, using the same logic of switching Fragmentsin and out (just using a different layout)?
  • 在这两种情况下,使用相同的切入和切Fragments出逻辑(只是使用不同的布局)保留 1 Activity 模型不是更容易吗?

This way most of the logic resides in the Fragmentsthemselves, and there is only a single Activity- less duplication of code.

通过这种方式,大部分逻辑都驻留在Fragments它们自身中,并且只有一个Activity- 更少的代码重复。

Also what I have read about the ActionBarSherlockis that it seems to work best with Fragmentsinstead of Activities(but I have not worked with it yet).

另外,我所读到的ActionBarSherlock是,它似乎最适合使用Fragments而不是Activities(但我还没有使用过它)。

Are the tutorials oversimplified, or have I missed something major in this approach?

教程是否过于简单,或者我是否错过了这种方法中的主要内容?



We have tried both approaches successfully in the office - but I am about to start a bigger project and want to make things as easy for myself as possible.

我们已经在办公室成功地尝试了这两种方法 - 但我即将开始一个更大的项目,并希望让自己尽可能轻松。

Some links to related questions:

一些相关问题的链接:



Updates

更新

Started bounty on question - still not convinced about why I need to duplicate my app logic in my tablet activity and in each phone activity.

开始悬赏悬赏 - 仍然不相信为什么我需要在平板电脑活动和每个手机活动中复制我的应用程序逻辑。

Also found an interesting article by the guys at Square, which is well worth reading:

在 Square 还发现了一篇有趣的文章,值得一读:

采纳答案by Stephen Asherson

I agree that the tutorials are very simplified. They just introduce Fragmentsbut I do not agree with the pattern as suggested.

我同意教程非常简化。他们只是介绍,Fragments但我不同意所建议的模式。

I also agree that it is not a good idea to duplicate your app's logic across many Activities (see DRY Principle on wikipedia).

我也同意在许多活动中复制应用程序的逻辑不是一个好主意(请参阅维基百科上的 DRY 原则)。



I prefer the pattern used by the ActionBarSherlockFragments Demo app (download hereand source code here). The demo that most closely matches the tutorial mentioned in the question is the one called "Layout" in the app; or FragmentLayoutSupportin the source code.

我更喜欢ActionBarSherlockFragments Demo 应用程序使用的模式(在此处下载在此处下载源代码)。与问题中提到的教程最匹配的演示是应用程序中称为“布局”的演示;或FragmentLayoutSupport在源代码中。

In this demo, the logic has been moved out of the Activityand into the Fragment. The TitlesFragmentactually contains the logic for changing Fragments. In this way, each Activity is very simple. To duplicate many very simple Activities, where none of the logic is inside the Activities, makes it very simple.

在此演示中,逻辑已移出Activity并移入Fragment. 该TitlesFragment实际上包含更改碎片的逻辑。这样,每个Activity就很简单了。复制许多非常简单的活动,其中没有逻辑在活动中,这使它变得非常简单。

By putting the logic into the Fragments, there is no need to write the code more than once; it is available no matter which Activity the Fragment is placed into. This makes it a more powerful pattern than the one suggested by the basic tutorial.

通过将逻辑放入 Fragment 中,无需多次编写代码;无论将 Fragment 放入哪个 Activity,它都可用。这使它成为比基本教程建议的更强大的模式。

    /**
    * Helper function to show the details of a selected item, either by
    * displaying a fragment in-place in the current UI, or starting a
    * whole new activity in which it is displayed.
    */
    void showDetails(int index)
    {
        mCurCheckPosition = index;

        if (mDualPane)
        {
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.
            getListView().setItemChecked(index, true);

            // Check what fragment is currently shown, replace if needed.
            DetailsFragment details = (DetailsFragment) getFragmentManager()
                .findFragmentById(R.id.details);
            if (details == null || details.getShownIndex() != index)
            {
                // Make new fragment to show this selection.
                details = DetailsFragment.newInstance(index);

                // Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
                FragmentTransaction ft = getFragmentManager()
                    .beginTransaction();
                ft.replace(R.id.details, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        }
        else
        {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), DetailsActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);
        }
    }


Another advantage of the ABSpattern is that you do not end up with a Tablet Activity containing lots of logic, and that means that you save memory. The tutorial pattern can lead to a very big main activity in a more complex app; since it needs to handle the logic of all the fragments that get placed in it at any time.

ABS模式的另一个优点是您不会以包含大量逻辑的 Tablet Activity 结束,这意味着您可以节省内存。教程模式可以在更复杂的应用程序中导致非常大的主要活动;因为它需要随时处理放入其中的所有片段的逻辑。

Overall, do not think of it as being forced to use many activities. Think of it as having the opportunity to split your code into many fragments, and saving memory when using them.

总体而言,不要将其视为被迫使用许多活动。将其视为有机会将您的代码拆分为许多片段,并在使用它们时节省内存。

回答by pjco

I think you're on the right track. (And yes, the tutorials are over-simplified).

我认为你在正确的轨道上。(是的,教程过于简化了)。

In a tablet layout, you could use a single Activity and swap in and out Fragments (in multiple 'panes'). While in a phone layout you can use a new Activity for each Fragment.

在平板电脑布局中,您可以使用单个活动并交换片段(在多个“窗格”中)。在手机布局中,您可以为每个 Fragment 使用一个新的 Activity。

Like so:

像这样:

enter image description here

在此处输入图片说明

It may seem like a lot of extra work, but by using multiple activities for phones, you enable basic Activity life-cycle and Intent passing. This also allows the framework to handle all the animations and the back-stack.

这看起来像是很多额外的工作,但是通过为手机使用多个 Activity,您可以启用基本的 Activity 生命周期和 Intent 传递。这也允许框架处理所有动画和返回堆栈。

To help reduce the code you can use a BaseActivityand extend from that.

为了帮助减少代码,您可以使用 aBaseActivity并从中扩展。

So if the user has a tablet you would use MyMultiPaneFragActivityor something similar. This activity is responsible for managing callbacks from the fragments and routing intents to the correct fragment (such as a search intent)

因此,如果用户有您会使用的平板电脑MyMultiPaneFragActivity或类似的东西。此活动负责管理从片段的回调并将意图路由到正确的片段(例如搜索意图)

If the user has a phone, you can use a regular Activity with very little code and have it extend MyBaseSingleFragActivityor something similar. These activities could be very simple, 5-10 lines of code (maybe even less).

如果用户有手机,您可以使用很少的代码使用常规活动,并扩展它MyBaseSingleFragActivity或类似的东西。这些活动可能非常简单,只需 5-10 行代码(甚至可能更少)。

The tricky part is routing intents and whatnot. *(Edit: see more below).

棘手的部分是路由意图等等。*(编辑:见下文)。

I think the reason this is the recommended way is to save memory and reduce complexity and coupling. If you are swapping out Fragments, the FragmentManagermaintains a reference to that Fragment for the back-stack. It also simplifies what should be 'running' for the the user. This setup also decouples the views and layout and logic in the Fragment from the Activity life-cycle. This way a Fragment can exist in a single activity, alongside another fragment (two-pane), or in a three-pane Activity, etc.

我认为这是推荐方法的原因是为了节省内存并减少复杂性和耦合。如果您要换出 Fragment,则FragmentManager它会为 back-stack 维护对该 Fragment 的引用。它还简化了应该为用户“运行”的内容。此设置还将 Fragment 中的视图、布局和逻辑与 Activity 生命周期分离。这样,一个片段可以存在于单个活动中,与另一个片段(两窗格)或三窗格活动等一起存在。

*One of the benefits of having regular intent routing is that you can launch an Activity explicitly from anywhere in the back-stack. One example might be in the case of search results. (MySearchResults.class).

*定期意图路由的好处之一是您可以从后台堆栈的任何位置显式启动 Activity。一个例子可能是搜索结果。(MySearchResults.class)。

Have a read here for more:

在这里阅读更多:

http://android-developers.blogspot.com/2011/09/preparing-for-handsets.html

http://android-developers.blogspot.com/2011/09/preparing-for-handsets.html

It might be a little more up-front work, because each fragment must work well across separate activities, but it usually pays off. It means that you can use alternative layout files that define different fragment combinations, keep fragment code modular, simplify action bar management, and let the system handle all the back stack work.

这可能需要更多的前期工作,因为每个片段必须在不同的活动中都能很好地工作,但通常会得到回报。这意味着您可以使用定义不同片段组合的替代布局文件,保持片段代码模块化,简化操作栏管理,并让系统处理所有后台堆栈工作。

回答by Aditya Naique

Here is Reto Meier's answer regarding the same, taken from this videoof Udacity's Android Fundamentals course.

这里是雷托·梅尔的关于相同的答案,从拍摄这段视频Udacity的Android基础课程

There are a number of reasons you'd be better off breaking your app into different activities.

  • Having a single monolithic activity increases the complexity of your code, making it difficult to read, test and maintain.
  • Makes creating and managing intent filters much harder.
  • Increases the risk of tightly coupling independent components.
  • Makes it much more likely to introduce security risks if the single activity includes both sensitive information and information that's safe to share.

A good rule of thumb is to create a new activity whenever the context changes. For example, displaying a different kind of data and while switching from viewing to entering data.

您最好将应用程序分解为不同的 Activity 的原因有很多。

  • 单一的单体活动会增加代码的复杂性,使其难以阅读、测试和维护。
  • 使创建和管理意图过滤器变得更加困难。
  • 增加紧密耦合独立组件的风险。
  • 如果单个活动同时包含敏感信息和可安全共享的信息,则更有可能引入安全风险。

一个好的经验法则是在上下文发生变化时创建一个新活动。例如,显示不同类型的数据以及从查看切换到输入数据。

回答by CommonsWare

One problem with this method, is that you duplicate a lot of the logic in the main Tablet Activity, and in the separate Phone Activities.

这种方法的一个问题是,您在主要 Tablet Activity 和单独的 Phone Activity 中复制了很多逻辑。

In the master-detail pattern, there are two activities. One shows both fragments on larger screens and only the "master" fragment on smaller screens. The other shows the "detail" fragment on smaller screens.

在主从模式中,有两个活动。一个在较大的屏幕上显示两个片段,在较小的屏幕上只显示“主”片段。另一个在较小的屏幕上显示“细节”片段。

Your detail logic should be tied up in the detail fragment. Hence, there is no code duplication related to detail logic between activities -- the detail activity merely displays the detail fragment, perhaps passing in data from an Intentextra.

您的详细逻辑应该绑定在详细信息片段中。因此,没有与活动之间的细节逻辑相关的代码重复——细节活动仅显示细节片段,可能从Intent额外的数据中传递。

Also what I have read about the ActionBarSherlock is that it seems to work best with Fragments instead of Activities (but I have not worked with it yet).

另外我读到的关于 ActionBarSherlock 的内容是它似乎最适合 Fragments 而不是活动(但我还没有使用过它)。

ActionBarSherlock has no more to do with fragments than does the native action bar, since ActionBarSherlock is purely a backport of the native action bar.

ActionBarSherlock 与原生操作栏相比与片段没有更多关系,因为 ActionBarSherlock 纯粹是原生操作栏的向后移植。

回答by EFlisio

Referring to the 1st question of "Is there a reason to split the phone app into many Activities?" - Yes. it simply comes down to the space available, a Tablet gives more room to developers, thus allowing developers to put more on one screen. Android tells us that Activities can provide a screen. So What you can do with 1 large screen on a tablet, is something that may have to be spread across multiple screens on a phone, because there's not enough room for all of the fragments.

参考第一个问题“是否有理由将手机应用拆分为多个Activity?” - 是的。它只是归结为可用空间,平板电脑为开发人员提供了更多空间,从而允许开发人员在一个屏幕上放置更多内容。Android 告诉我们活动可以提供一个屏幕。所以你可以用平板电脑上的 1 个大屏幕做的事情,可能必须分布在手机的多个屏幕上,因为没有足够的空间容纳所有的碎片。