[android] Why fragments, and when to use fragments instead of activities?

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?

The answer is


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


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.


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


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.

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.

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.


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.


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.


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


Adding to above answers, I shall tell using example of an app I released on playstore.

This was the first app I developed when learning android there fore I worked only with activities There are multiple activity pages I think about 12. Most of these had content that could be reused in other pages yet I ended up with a separate activity page for almost every single click on the app. Once I learnt fragments I realised how all reusables could just be implemented and separate fragments and just be used with very few activities. My user may not see any difference, but the same can be done with lesser code besides fragments are light weight, apart from the reusability and modularity they offer.


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.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items

Examples related to android-3.0-honeycomb

Why fragments, and when to use fragments instead of activities? How to implement the Android ActionBar back button? How to hide action bar before activity is created, and then show it again? Android replace the current fragment with another fragment getActionBar() returns null Fragments onResume from back stack How to set a Fragment tag by code? Android: How to change the ActionBar "Home" Icon to be something other than the app icon? ActionBar text color Unable to resolve host "<insert URL here>" No address associated with hostname