Why fragments, and when to use fragments instead of activities?

AndroidAndroid LayoutAndroid FragmentsAndroid ActivityAndroid 3.0-Honeycomb

Android Problem Overview


In Android API 11+, Google has released a new class called Fragment.

In the videos, Google suggests that whenever possible (link1, link2), we should use fragments instead of activities, but they didn't explain exactly why.

What's the purpose of fragments and some possible uses of them (other than some UI examples that can be easily be achieved by simple views/layouts)?

My question is about fragments:

  1. What are the purposes of using a fragment?
  2. What are the advantages and disadvantages of using fragments compared to using activities/views/layouts?

Bonus questions:

  1. Can you give some really interesting uses for fragments? Things that Google didn't mention in their videos?
  2. What's the best way to communicate between fragments and the activities that contain them?
  3. What are the most important things to remember when you use fragments? Any tips and warnings from your experience?

Android Solutions


Solution 1 - Android

> #1 & #2 what are the purposes of using a fragment & what are the > advantages and disadvantages of using fragments compared to using > activities/views/layouts?

Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;

  • The ActionBar. If you want tabs up there to navigate your app, you quickly see that ActionBar.TabListener interface gives you a FragmentTransaction as an input argument to the onTabSelected method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.

  • The FragmentManager handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.

  • You can use the cool ViewPager with a FragmentPagerAdapter to create swipe interfaces. The FragmentPagerAdapter code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.

  • Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.

  • You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use ActionBarSherlock and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like the ActionBar, with tabs, overflow, split action bar, viewpager etc.

> Bonus 2

The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity() with data on it. The intent is passed on to all fragments of the activity you launch.

Solution 2 - Android

Not sure what video(s) you are referring to, but I doubt they are saying you should use fragments instead of activities, because they are not directly interchangeable. There is actually a fairly detailed entry in the Dev Guide, consider reading it for details.

In short, fragments live inside activities, and each activity can host many fragments. Like activities, they have a specific lifecycle, unlike activities, they are not top-level application components. Advantages of fragments include code reuse and modularity (e.g., using the same list view in many activities), including the ability to build multi-pane interfaces (mostly useful on tablets). The main disadvantage is (some) added complexity. You can generally achieve the same thing with (custom) views in a non-standard and less robust way.

Solution 3 - Android

A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity which enable a more modular activity design. It will not be wrong if we say a fragment is a kind of subactivity.

Following are important points about a fragment:

  1. A fragment has its own layout and its own behavior with its own lifecycle callbacks.

  2. You can add or remove fragments in an activity while the activity is running.

  3. You can combine multiple fragments in a single activity to build a multi-pane UI.

  4. A fragment can be used in multiple activities.

  5. The fragment life cycle is closely related to the lifecycle of its host activity.

  6. When the activity is paused, all the fragments available in the acivity will also be stopped.

  7. A fragment can implement a behavior that has no user interface component.

  8. Fragments were added to the Android API in Android 3 (Honeycomb) with API version 11.

For more details, please visit the official site, Fragments.

Solution 4 - Android

This is important information that I found on fragments:

> Historically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. Instead the object must be serialized or a globally accessible reference made available. > > By making each screen a separate Fragment, this data passing headache > is completely avoided. Fragments always exist within the context of a > given Activity and can always access that Activity. By storing the > information of interest within the Activity, the Fragment for each > screen can simply access the object reference through the Activity.

Source: https://www.pluralsight.com/blog/software-development/android-fragments

Solution 5 - Android

Activities are the full screen components in the app with the toolbar, everything else are preferably Fragments. One full screen parent activity with a toolbar can have multiple panes, scrollable pages, dialogs, etc. (all fragments), all of which can be accessed from the parent and communicate via the parent.

Example:

Activity A, Activity B, Activity C:

  • All activities need to have same code repeated, to show a basic toolbar for example, or inherit from a parent activity (becomes cumbersome to manage).
  • To move from one activity to the other, either all of them need to be in memory (overhead) or one needs to be destroyed for the other to open.
  • Communication between activities can be done via Intents.

vs

Activity A, Fragment 1, Fragment 2, Fragment 3:

  • No code repetition, all screens have toolbars etc. from that one activity.
  • Several ways to move from one fragment to next - view pager, multi pane etc.
  • Activity has most data, so minimal inter-fragment communication needed. If still necessary, can be done via interfaces easily.
  • Fragments do not need to be full screen, lots of flexibility in designing them.
  • Fragments do not need to inflate layout if views are not necessary.
  • Several activities can use the same fragment.

Solution 6 - Android

Fragments are of particular use in some cases like where we want to keep a navigation drawer in all our pages. You can inflate a frame layout with whatever fragment you want and still have access to the navigation drawer.

If you had used an activity, you would have had to keep the drawer in all activities which makes for redundant code. This is one interesting use of a fragment.

I'm new to Android and still think a fragment is helpful this way.

Solution 7 - Android

I know this was already discussed to death, but I'd like to add some more points:

  • Frags can be used to populate Menus and can handle MenuItem clicks on their own. Thus giving futher modulation options for your Activities. You can do ContextualActionBar stuff and so on without your Activity knowing about it and can basically decouple it from the basic stuff your Activity handles (Navigation/Settings/About).

  • A parent Frag with child Frags can give you further options to modulize your components. E.g. you can easily swap Frags around, put new Frags inside a Pager or remove them, rearrange them. All without your Activity knowing anything about it just focusing on the higher level stuff.

Solution 8 - Android

A fragment lives inside an activity, while an activity lives by itself.

Solution 9 - Android

Fragments lives within the Activity and has:

  • its own lifecycle
  • its own layout
  • its own child fragments and etc.
Think of Fragments as a sub activity of the main activity it belongs to, it cannot exist of its own and it can be called/reused again and again. Hope this helps :)

Solution 10 - Android

If you've ever written front-end before, so used front-end components like(React, Vue or Angular). Think about fragments like reusable components within an activity.

Solution 11 - Android

1.Purposes of using a fragment?

  • Ans:
  1. Dealing with device form-factor differences.
  2. Passing information between app screens.
  3. User interface organization.
  4. Advanced UI metaphors.

Solution 12 - Android

Fragment can be thought of as non-root components in a composite tree of ui elements while activities sit at the top in the forest of composites(ui trees).

  • A rule of thumb on when not to use Fragment is when as a child the fragment has a conflicting attribute, e.g., it may be immersive or may be using a different style all together or has some other architectural / logical difference and doesn't fit in the existing tree homogeneously.

  • A rule of thumb on when to prefer Activity over Fragment is when the task (or set of coherent task) is fully independent and reusable and does some heavy weight lifting and should not be burdened further to conform to another parent-child composite (SRP violation, second responsibility would be to conform to the composite). For e.g., a MediaCaptureActivity that captures audio, video, photos etc and allows for edits, noise removal, annotations on photos etc and so on. This activity/module may have child fragments that do more granular work and conform to a common display theme.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionandroid developerView Question on Stackoverflow
Solution 1 - AndroidGlenn BechView Answer on Stackoverflow
Solution 2 - AndroidNikolay ElenkovView Answer on Stackoverflow
Solution 3 - AndroidmaniView Answer on Stackoverflow
Solution 4 - AndroidKaveesh KanwalView Answer on Stackoverflow
Solution 5 - AndroidChandrima BhattacharjeeView Answer on Stackoverflow
Solution 6 - AndroidNithin BabyView Answer on Stackoverflow
Solution 7 - AndroideinschnaehkeeeView Answer on Stackoverflow
Solution 8 - AndroidsuperkytozView Answer on Stackoverflow
Solution 9 - AndroidmaniixView Answer on Stackoverflow
Solution 10 - AndroidDamola ObalekeView Answer on Stackoverflow
Solution 11 - AndroidPrithiv DharmarajView Answer on Stackoverflow
Solution 12 - AndroidAbhinav AtulView Answer on Stackoverflow