Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do fragments cause fat activities?

Recently I was given the task of building an app which is rather like a book. The high-level design was basically a couple of list views showing chapters, then drill-down into a list of topics then onto a page itself. There were a number of other list-type views which displayed bookmarks or text search results and there was a fair amount of animation, sliding one fragment off and another on at the same time. This was my first use of fragments and although they first appear to be a good encapsulation of a piece of UI functionality, I can't help wondering if their use, as in my case, leads to 'fat' Activity classes, having to manage several different fragments and having to implement several interfaces which they publish.

As an example showing the interfaces implemented by one Activity:

public class NodeListActivity extends Activity implements 
        NodeListFragment.OnItemSelectedListener,
        SearchListFragment.OnItemSelectedListener,
        NodeFragment.OnLinkSelectedListener,
        OnCloseSelectedListener,
        OnActionBarItemSelectedListener,
        OnBookmarkSelectedListener

On older versions of Android, I would have created a separate Activity for each main screen/function. Is this a code smell or does the combination of several fragments and animations lead to fat Activities?

like image 643
John J Smith Avatar asked Jan 28 '14 22:01

John J Smith


1 Answers

does the combination of several fragments and animations lead to fat Activities?

Yes. However, that is becoming more common, and therefore less code smelly.

What is somewhat smelly is that loooooooooooooooooooong list of interfaces. :-)

For something that complex, you might find that using an event bus (Square's Otto, greenrobot's EventBus, or even LocalBroadcastManager) is a cleaner approach. Rather than having fragments use an interface to tell their hosting activity about an event (which is my guess as to the source of all your interfaces), the fragment can post an event to the bus, which the hosting activity can subscribe to. This does add a smidge of runtime overhead, but adds the benefit of avoiding all the interfaces. It can also be extended to other components, such as a service posting an event when something happens in the background that the UI layer, if it exists, needs to know about.

like image 96
CommonsWare Avatar answered Oct 15 '22 04:10

CommonsWare