625

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?
nbro
  • 15,395
  • 32
  • 113
  • 196
android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • 3
    Possible duplicate of [Dilemma: when to use Fragments vs Activities:](http://stackoverflow.com/questions/20306091/dilemma-when-to-use-fragments-vs-activities) – Ciro Santilli OurBigBook.com Feb 09 '16 at 14:18
  • Related post - [What are the differences between activity and fragment](https://stackoverflow.com/q/25822656/465053) & [what is the difference between view and activity in android development?](https://stackoverflow.com/q/6952184/465053) – RBT Aug 14 '18 at 09:15
  • an activity can be thought of as an independent micro-service while a fragment can be thought of as an embeddable dependency – Abhinav Atul Feb 16 '21 at 11:08

13 Answers13

356

#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.

Glenn Bech
  • 6,103
  • 4
  • 39
  • 56
  • 8
    first of all ,thanks.i appreciate people who give informative(yet short) answers and not just give me a link to a manual .anyway, besides extra features to work on special classes , can you think of advantages and disadvantages of working with fragments? – android developer May 09 '12 at 14:48
  • 4
    I think you have to be more direct in you questioning. I just gave four major advantages above. – Glenn Bech May 09 '12 at 17:48
  • 3
    ok , what about disadvantages compared to customized views and activities? – android developer May 09 '12 at 19:21
  • 2
    how do you communicate between fragments using intents? do all fragments need to be "alive" (added to the activity) so that they could communicate with each other? – android developer Jan 02 '13 at 21:32
  • 79
    One fragment should never talk directly to another fragment - instead go through the parent activity. This way you don't end up with spaghetti code but easy to manage code. – slott Nov 04 '13 at 19:18
  • 2
    I've always been looking at fragments as something similar to Web partial views.. and I'm starting to understand that I was wrong or, better, that I wasn't right. Thanks for the explanation @GlennBech, I'm gonna take your answer as a cue to pursue the matter ;) – andrea.rinaldi Apr 01 '14 at 07:11
  • 2
    the larger question is how does a developer know when to use a fragment and when not to use a fragment? – Kaveesh Kanwal Sep 04 '15 at 04:08
  • 1
    FWIW, It seems to me the heart of your answer is `reusable`, in `Fragments are ... reusable user interfaces`. This suggests that they are appropriate/worthwhile if you expect to use them in more than one activity. But the details of your answer are not much about `re-use`. A better term might be `modular`. A simple app that is merely a series of screens is fine as a series of activities. Once your design has a more complex flow or structure, it is often easier to maintain state in an activity, and have that activity manage some fragments. (BTW, true even if the fragments are full-screen.) – ToolmakerSteve Sep 20 '16 at 15:15
  • 11
    Re *"The best way to communicate between fragments are intents"* Huh? I don't think so. intents are for communicating between *activities*. The way to communicate "between fragments" is .. don't. That is, don't communicate directly fragment-to-fragment, instead a fragment should do a callback in a custom interface to its owning activity, which decides what to do. – ToolmakerSteve Sep 20 '16 at 15:57
  • @ToolmakerSteve I don't totally agree. Callbacks can get quite messy. If an activity has three fragments which can emit two "events", the host activity will have to implement six methods. From a Java architectural point of view, these methods belong to the fragments, (Cohesion), as they typically will manipulate on the state of fragments. If you think of user interface action as events, and use intents or broadcasts to communicate them, you can get very clean code where fragments react to outside events and update their internal state themselves. – Glenn Bech Sep 23 '16 at 06:03
  • @slott its not only about spaghetti code but it defeats the use case of reusability....only important property of being reusable component is they should not know anything about outside world. – Amit Kaushik Dec 23 '17 at 10:48
  • 1
    @GlennBech - ahh, you are describing a situation where multiple fragments are active *at the same time*, so it makes sense for them to react to a broadcast message. I was thinking of a different situation, where one fragment is passing information "forward" to another fragment that may not yet exist. So in my mind, it was easier to simply pass an object back to the activity, which already had logic to instantiate the second fragment. Then it was up to the activity to decide how best to pass that information to the new fragment. – ToolmakerSteve May 05 '18 at 21:02
  • 1
    @GlennBech .. or you are describing a design which relies on launching new activities, rather than managing fragments within a single activity. You say *"When you press something in a Fragment you would typically call StartActivity() with data on it. .. the activity you launch."* But that is my point: *intent* is meaningful *when communicating with another activity*; IMHO it isn't "best" solution when manipulating fragments themselves *without* starting another activity. – ToolmakerSteve May 05 '18 at 21:19
85

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.

Nikolay Elenkov
  • 52,576
  • 10
  • 84
  • 84
  • 1
    updated question . it now has links to the videos of google. also, thanks for the explanation, but i still need clarification about my question. – android developer May 07 '12 at 11:04
  • 6
    Read the dev guide entry, it has more than enough details. It's unlikely that you will get an answer to 'cool uses of fragments' on SO -- way to vague and there is no single answer. Number 4 is specificlly answered in the dev guide-- http://developer.android.com/guide/topics/fundamentals/fragments.html#CommunicatingWithActivity – Nikolay Elenkov May 07 '12 at 12:40
  • 1
    as far as i know , this method creates a dependency of which activity can contain which fragment . also , please answer the main questions (the first two) . – android developer May 07 '12 at 17:06
  • 3
    Thanks to android developer for insisting on answers to the basic question. ATM I've not seen anything useful to me in the Fragment class over using the XML "include" tag. The kinds of things that I would find valuable would be the ability to specify one layout that would magically morph into the best user experience at all resolutions. From what I can tell you still need to do that in code by yourself. Another potential value would be a way to bundle code + resources into reusable components not found in the reusing apps, but again does not appear to be there. I want one really good reason. – Melinda Green Aug 13 '13 at 02:16
  • 2
    I'm starting to understand the way Google suggest using fragments, but I fairly agree with @NikolayElenkov.. To me, using Activities still seems to be the most robust and the less complex way.. – andrea.rinaldi Apr 01 '14 at 07:14
  • it still doesn't really answer why not just use custom views or how fragments are that much different from custom views, with which you can do all the same things and re-usability as well. the answer to that is that google doesn't want you to use custom views and provides you with fragments instead. unfortunately a bunch of android best practice choices are like this. – Lassi Kinnunen Feb 28 '18 at 15:41
68

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mani
  • 3,394
  • 3
  • 30
  • 36
  • 1. As you mentioned on #8, it doesn't have to have a layout. 6. you missed the part after "means" . Anyway, thanks for helping others make this clearer. I will give you +1 . – android developer May 23 '14 at 14:09
  • 2
    Regarding #8, a possible example of no-layout fragment (i.e. 'headless' fragment) would be one that carries out a task that despite being somewhat short (such as a short HTTP request) is still required to survive configuration changes and thus depends on the exact fragment instance being preserved across them (by using setRetainInstance(true) on the fragment). As for layout fragments, setRetainInstance(true) doesn't make much sense, as it prevents resources associated with their views from being freed up when necessary (i.e. a memory leak). – Piovezan Mar 04 '15 at 14:02
  • NOTE: "#8" is now "#7". – ToolmakerSteve Sep 20 '16 at 15:35
39

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.
Pang
  • 9,564
  • 146
  • 81
  • 122
33

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

Pang
  • 9,564
  • 146
  • 81
  • 122
Kaveesh Kanwal
  • 1,753
  • 17
  • 16
  • 3
    That's true, but there are solutions for this: use Parcelable when it's not a huge object (and there is a plugin to make it easier), and if it's a huge object, you can always use a static reference that will be set to null when you get to the new activity (or when you destroy it, depending on your requirement). – android developer Sep 04 '15 at 07:08
  • @androiddeveloper: "use Parcelable" fits my definition of a "data passing headache that is avoided by using Fragments". If there is complex shared state that needs to persist while a series of screens passes by, an Activity + Fragments is a good solution, IMHO. (Though I abandoned the Fragment back stack, and did my own managing of what "back" means.) – ToolmakerSteve Sep 20 '16 at 15:48
  • 1
    Using interface design pattern between fragments through a container activity is a much modular approach to pass not just objects but also click event listeners and method arguments back to other fragments or to the main container activity. – Kaveesh Kanwal Nov 25 '16 at 07:45
11

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nithin Baby
  • 7,486
  • 4
  • 21
  • 25
  • 1
    Yes. However, I'm still sometimes confused about the correct way to use fragments, and that's because of the complex lifecycle of both fragments and activities. – android developer Dec 15 '14 at 18:13
  • @androiddeveloper do you just use activities mostly? – Michael Alan Huff May 14 '15 at 20:57
  • @MichaelAlanHuff When supporting tablets, I think it's better to use Fragments. Also, when supporting orientation changes and other similar events, you might want to use DialogFragment, as it allows you to restore them – android developer May 14 '15 at 21:24
  • @androiddeveloper, that's what I think as well. I haven't used DialogFragments as often. For helping modularity of logic, a lot of android developers are starting to use custom views to hold the logic a la square's mortar. Here is a recent talk on custom views given by an engineer from Airbnb https://vimeo.com/127799187 – Michael Alan Huff May 14 '15 at 21:31
  • @MichaelAlanHuff using fragments could be also useful if you think the current screen could be a part of another screen. – android developer May 14 '15 at 22:12
  • there really would be nothing stopping you from just creating the views in the same activity though or using custom views. what fragments do is provide you some boilerplate to take care of things for creating a "custom view" in a kind of a standard manner. fragments were created in a time when google best practice preachers didn't even mention possibilities of creating your own views. – Lassi Kinnunen Feb 28 '18 at 15:45
5

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.

einschnaehkeee
  • 1,858
  • 2
  • 17
  • 20
4

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.

Abhinav Atul
  • 601
  • 6
  • 14
3

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

Darren Finch
  • 15
  • 1
  • 4
superkytoz
  • 1,267
  • 4
  • 23
  • 43
3

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 :)

maniix
  • 51
  • 3
2

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.

1

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.
Prithiv Dharmaraj
  • 357
  • 2
  • 4
  • 17
0

Why fragments?

Fragments were created to replace most of the activity use cases. And see this Android Dev Summit session.

When to use fragments instead of activities?

Always, unless you really need an API that is only available in activity.

k4dima
  • 6,070
  • 5
  • 41
  • 39