数据加载安卓活动/片段责任片段、加载、责任、数据

2023-09-04 08:21:36 作者:别碰我的柠檬

当启动一个客户端的新的应用程序,我再一次问自己,谁应该负责加载数据的相同问题:活动或片段。我已经采取这两种选择对各种应用程序,我想知道哪些模式是按照最好的给你在以下方面:

When starting a new application for a client, I am asking myself again the same question about who should be responsible for loading data: activities or fragments. I have taken both options for various apps and I was wondering which pattern is best according to you in terms of:

限制了code的复杂性。 在处理边界情况(如屏幕旋转,屏幕会省电,连接丢失,等等。)

这使得有那些刚刚喂了一堆对象,以显示片段。他们一无所知加载数据,以及我们如何加载。

This allows to have fragments that are just fed a bunch of objects to display. They know nothing about loading data and how we load that.

在另一侧,利用活动负荷数据取方法是必需的(例如最初的最新的50个条目,并在一个搜索,加载搜索结果)。它然后将其传递到其显示它的片段。方法加载的数据可以是任何东西(从服务,从数据库,...片段只知道的POJO)

On the other side, the activity loads data using whichever method is required (for instance initially the latest 50 entries and on a search, loads the search result). It then passes it to the fragment which displays it. Method to load the data could be anything (from service, from DB, ... fragments only know about POJOs)

这是怎样的一个MVC架构,其中的活动是控制器和碎片的看法。

It's kind of a MVC architecture where the activity is the controller and fragments are the view.

在这种模式中,片段是自主件的应用。他们知道如何加载它们显示的数据以及如何将其展示给用户。

In this pattern, fragments are autonomous pieces of application. They know how to load the data they are displaying and how to show it to the user.

活动只是一种方式来安排画面片段,并协调应用程序的活动之间的转换。

Activities are simply a way to arrange fragments on screen and to coordinate transitions between application activities.

推荐答案

在理想情况下既不活动片段 与UI 应该包含任何模式的逻辑 - 这些类应该是重量轻,只为UI逻辑负责。但是,当你决定做一个单独的模型对象,你有一个两难选择在何处初始化并存储该对象和如何处理配置更改。这里谈到了一些方便的技巧:

Ideally neither Activity nor Fragment with UI should contain any "model" logic - these classes should be lightweight and responsible only for UI logic. But when you decide to make a separate model object you have a dilemma to choose where to initialise and store this object and how to deal with configuration changes. And here comes some handy trick:

您可以创建一个模式 片段 没有UI ,使它的保留实例的处理配置变化(这是AFAIK保存整个配置数据最简单的方法。更改,而无需麻烦)和检索它的任何地方,你通过 findFragmentById需要()。你让所有的昂贵的操作里面一次(使用后台线程,当然),存储你的数据,你就大功告成了。 欲了解更多信息,请参见添加无UI 部分片段。

You can create a model Fragment without UI, make it retain instance to deal with configuration changes (it's AFAIK the simplest way to save data across config. changes without troubles) and retrieve it anywhere you need via findFragmentById(). You make all expensive operations inside it once (using background thread, of course), store your data and you're done. For more info, see Adding a fragment without a UI section.