When and Why Should I Use Fragments in Android Applications

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

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

When and why should I use fragments in Android applications?

Fragments are more of a UI benefit in my opinion. It's convenient for the user sometimes to see two different views of two different classes on the same screen. If, in your moment of creativity, you decide it would be nice to display your application with, say, a listView that takes up half the screen and a webView that takes up the other half - so that when you click on a list item in fragment A it passes an intent to the webView in fragment B, and suddenly you see what you just clicked without the app switching activities - then you could use a fragment. That's just an example I came up with off the top of my head.

Bottom line: Fragments are two or more activities on the screen at the same time.

Should I use fragments or activities for my app?

For me, all decisions about Activity or Fragment are related to (1) UX (2) Manageability (3) Communication cost across components, etc.

Let me introduce some decisions by examples.

  1. Is the screen required to launch from outside (Share intent)?

    • Activity is better as it can be opened directly from what AndroidManifest gives.
  2. Does the screen require page-by-page views (recipe pages)?

    • Fragment is better as Fragment+ViewPager give flexible paging fuctionality. Moreover, some Android devices or theme editors override Activity opening effects so page-turning animation does not run as expected if we implements it in Activity-by-Activity manner.
  3. Does the screen execute Camera or Photo intent with StartActivity?

    • Activity is better as OnActivityResult is hard to manage inner fragments when the app restores back from the Camera apps. For this reason, "writing a post" screen could be a good example to be a single Activity.
  4. Does the screen have to run regardless of screen on/off (Timers)?

    • Activity is better as it can show up faster and lighter without Activity-Fragment dancing.
  5. Does the screen have a kind of master-detail hierarchy?

    • Fragment is better because we could prepare tablet layout.
  6. Does the screen consume memory a lot?

    • Activity is better because we can focus on the activity solely not inner fragments memory usage.
  7. Does the screen has nested fragments more than 3-depth?

    • Fragment, reluctantly. Communication between fragment is unstable and Activity-Fragment bridging/dancing is always headache 1 2. We can make complexity lower but Activity-inside-Fragment-inside-ViewPager-inside-fragment-... is hard to acheive manageability.

Using multiple Fragment with single Activity is recommended by professional Android developers but we could decide to create more Activities for easier management and faster understanding.

In your case, I would like to implement components as below.

  • MainActivity with Fragments: Ingredients, Categories, Recipe.
  • ResultActivity with Fragments: Search and its Results are a kind of master-detail view.
  • TimerActivity: It should be good to run in single Activity.
  • RecipeActivity: If each recipe has its own id and can be shared as permalink, your app could open directly the recipe page by RecipeActivity. And, it could be better to show recipe even if your app is restored from turned-off or switched back from another app situation.

Why should I use fragment in Android?

From documentation

You can think of a fragment as a modular section of an activity, which
has its own lifecycle, receives its own input events, and which you
can add or remove while the activity is running (sort of like a "sub
activity" that you can reuse in different activities).

Some advantages are..

  1. A particular UI part, once done in fragment, can be reused in
    same/different activities.
  2. You can separate different sections of UI, hence code will be neat,
    and easy readable.

The ability of fragment to be able to reuse is very helpful when you are creating applications for different kind of android devices (phones, tablets). A well designed fragment can be just plugged into your UI hierarchy.

When to use and when not to use fragments in Android?

A fragment is an independent component which can be used by an
activity. A fragment encapsulate functionality so that it is easier to
reuse within activities and layouts.

http://www.vogella.com/articles/AndroidFragments/article.html#fragments

but in others tutorials say that if I want or only when my app is for Tablets

Those tutorials you mentioned probably meant this:

Fragments make it easy to reuse components in different layouts, e.g.
you can build single-pane layouts for handsets (phones) and multi-pane
layouts for tablets. This is not limited to tablets; for example you
can use fragments also to support different layout for landscape and
portrait orientation on a smartphone.

http://www.vogella.com/articles/AndroidFragments/article.html#fragments_usage

When there is a big screen you don't want to leave empty space. When the screen is too small you don't want squeeze everything. The solution is to have 2 different layouts reusing as much code as possible. That is when Fragments are especially handy.

What is the benefit of using Fragments in Android, rather than Views?

The main reason to use Fragments are for the backstack and lifecycle features. Otherwise, custom views are more light weight and simpler to implement.

At first, I actually tried to build a phone/tablet app using custom views. Everything appeared to work across phones AND tablets, even switching from single panel to split panel. Where I ran into trouble was with the back button and life cycle. Since I was simply updating views manually...there was nothing keeping track of the history of views and their states. Therefore, the back button did not work as expected and it was difficult to recreate even the latest state during life cycle events, such as when rotating the app. To fix that, I had to wrap my custom views in fragments and use the FragmentManager so that the previous states would be saved and recreated.

I realized after answering that I posted to a similar question a year earlier: https://stackoverflow.com/a/11126397/618881

Why use Fragments?

The main reason is that fragments are more reusable than custom views.

Sometimes you can't create a fully encapsulated UI component relying on views alone. This is because there are things you would want to put into your view but can't because only an Activity can handle them, thus forcing tight coupling between an Activity and a View.

Here is one such example. Lets say you want to create a reusable UI component that, among many things, want to capture a photo and do something with it. Traditionally you would fire an intent that starts the camera and returns with the captured image.

Notice that your custom UI component can't fully encapsulate this functionality because it will have to rely on hosting Activity's startActivityForResult because views don't accept activity results (they can indirectly fire an intent through context).

Now if you wanted to reuse your custom UI component in different activities you would be repeating the code for Activity.startActivityForResult.

Fragment on the other hand cleanly solve this problem.

Similarly your fragment can contribute items to your options menu, something traditionally only an Activity could do. Again this could be important if the state of your custom view dictates what goes in the menu.

To Fragment or not to Fragment - Nested Fragments against Activities. Why should I use more than one Activity?

First off, I will agree with you that it is possible to write a huge application using only one activity and nested fragments. That's the fun of software - you can achieve the same functionality using a variety of approaches. For me, the choice to use multiple activities comes down to my personal preferences for encapsulation, reusability, and testability.

If I have a widget that can be reused in other applications, I make it a Fragment. For example, my app features a "sync with server" button and I have created a custom Fragment that uses Progress Bars to visually show the synchronization process. It's easy to imagine another application being able to use this widget, so that's why I developed it as a Fragment.

If I am switching tasks within my app, such that the new task is conceptually independent of the previous task, then I use a new activity. For example, the first page of my app asks you to select a user. Once you've clicked on a user, I send you to the main menu for that user. This main menu for the user is displayed in a new activity.

Now let's imagine a large, complex app, and a team of developers assigned to develop that app. If the app can be divided into separate activities, it is conceptually very easy to divide up the tasks. Each activity is its own sandbox, so parallel development is simple and unit-testable. If there are any common needs, the team should still develop Fragments and reuse them, of course. I should add that code reuse does not happen often enough in software development, but if done right, there should be a lot of reusable Fragments.

Now suppose it is time to test the app. Your testing team can treat each activity as its own black box. This is easier to test than a single huge app that relies on a single activity and tons of nested fragments. This is especially important if a bug exists. If a bug exists that is not obvious, at least I know the scope of the bug is limited to a single activity out of many.

In summary, my guess is that you are developing your app as an individual, and therefore your development decisions do not affect anybody else. Your perspectives would likely change if you were developing an app with a larger team, and I hope my response makes a lot of sense in that light.



Related Topics



Leave a reply



Submit