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

Inspired Android Developer Guide I am trying to write code in which all fragments are autonomous (in terms of network / logic) and any actions that they perform (click / tap) that should lead to the launch of a new action / fragment will be delegated to activity ( via callback).

For a start, this seemed right. But now that I have fragments that have more than 1 such widgets (which need a fragment to go to a new screen), it seems like a mess. I need to either write some callbacks or make some switch-case logic in the Activity for different actions on the fragment.

If this design sounds bad, what are the scenarios in which implementing callbacks (as suggested by management) would be a good idea?

+3
source share
1 answer

I do not know how you perform these callbacks.

One approach to this problem is to use a contract template:

  • The fragment defines the interface Contractthat any hosting hosting should perform.

  • When a fragment wants to transfer activity control, it calls a method on this interface

Jake Wharton has a canonical implementation of this on the GitHub gist . The only fragment that is not shown is that to work with it you MyCoolFragmentneed to implement an interface MyCoolFragment.Contract.

, , , , . , , Contract .

(, , ), > , .

, , . , , , , ( , ..).

+8

All Articles