Is it a good idea for a Fragment to delegate all navigation control to Activity?

android, android-fragments

Solution

I don't know how you are implementing these callbacks.

One approach to this problem is to use the contract pattern:

The fragment defines a `Contract` interface, that any hosting activity must implement

When the fragment wants to pass control to the activity, it calls a method on that interface

Jake Wharton has the canonical implementation of this in a GitHub gist. The only piece that is not shown is that the activity that hosts his `MyCoolFragment` needs to implement the `MyCoolFragment.Contract` interface.

This assumes that each fragment has distinct events to raise to the activity and therefore needs its own interface. If you have several fragments with common characteristics, you could standardize on a single interface, rather than duplicating the `Contract` everywhere.

There are other approaches (e.g., the comment on the gist suggesting using a message bus), but for simple fragment->activity communication, the contract pattern should have the least overhead, both in terms of coding and runtime implementation.

Your general approach, though, of delegating work to the activity where that work may result in changes to another fragment, is definitely a good one. It makes it that much easier to handle the cases where the fragments are not on the screen at the same time, perhaps hosted by different activities, as you handle different screen setups (phone vs. tablet, single screen vs. displaying content on a connected TV, etc.).

Problem

Inspired by the Android developer guide I am trying to write code in which all fragments are self-contained (in terms of network/logic) and any actions they perform (click/tap) which should result in launching a new activity/fragment would be delegated to the activity (through callback). To begin with, it seemed right. But now , when I have fragments which have more than 1 such widgets (which need the fragment to navigate to a new screen), it seems like a mess. I either need to write multiple callbacks or do some switch-case logic in Activity for different actions done on a fragment. If this design sounds bad, what are the scenarios where implementing callbacks (as suggested by the guide) would be a good idea ?

Original source