UPDATE: 5 years later this post is pretty out of date. Some of it still holds, but it is now possible to better architect primarily “single Activity” apps, especially with the advent of the android Navigation component. For posterity the post below remains…

When asking “should I use a Fragment or Activity?” it’s not always immediately obvious on how you should architect an app.

My advice is try to avoid a single “god” Activity (h/t Eric Burke) that manages navigation between tens of Fragments – it may seem to give you good control over transitions, but it gets messy quickly*.

My go to is always to use a combination of Activities and Fragments. So here are some tips:

  • If it’s a distinct part of an app (News, Settings, Write Post), use a new Activity. This Activity may be fairly light-weight, simply inflating a Fragment in its layout XML or in code.
  • For everything else use Fragments.
  • This gives you flexibility when combining Fragments in Activity layouts for tablet.
  • Create a BaseActivity class which handles setup/styling of ActionBar and SlidingDrawerLayout if you have that kind of navigation.
  • Nullify or customise the transitions between Activities if for example if you don’t want to have an obvious transition with an ActionBar that’s already in place (and you can make use of new L Activity transitions to smoothly transitions).
  • Fragments don’t need to be visual, an Activity can use the FragmentManager to create a persistent headless Fragment with setRetainInstance() who’s job may be to perform a background task (update, upload, refresh) – this means the user can rotate the device without destroying and recreating the Fragment, and is sometimes and alternative to binding to a Service onResume().

Some good sources for how to architect apps, as always the Google I/O Schedule app:

https://github.com/google/iosched

and Eric Burke’s 2012 talk, around half-way through:

http://www.infoq.com/presentations/Android-Design/

*When does it get messy?

  • When dealing with deeper hierarchies, and with navigational requests that come from a user action within a Fragment.
  • When you need the ActionBar to be in overlay mode (for a full screen experience) but only in certain screens.
  • When you need to create new tasks (either shooting off to another app and back, or allowing other apps to start Activities in your app to do something like with a Share action)
  • There are many more, please feel free to add some in the comments if you can think of any.