What Is the Benefit of Using Fragments in Android, Rather Than Views

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

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.

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.

When to use fragments over views?

A fragment has a life cycle of its own , so you don't have to worry about memory and objects in larger screens where this does matter.

Are Fragments and Fragment Activities inherently faster than Activities?

I became a believer in Fragments in my last application. Whether or not they are computationally faster, they feel faster because you can swap them in and out basically instantaneously, including full support for the back stack if you do it right (call addToBackStack() on the transaction, or something very similar).

I now use Fragments / Fragment activity for all navigation I want to feel very quick, like clicking on a row to get more details. I only launch new activities for when I want to do a fundamentally different thing and have a clean slate to work with. For instance, I usually have a LoginActivity that deals exclusively with logins/registrations, and at least one more that is the core of the app.

But the fundamental benefit of Fragments still remains their flexibility. I can show fragments on top of other fragments, re-arrange them on different screen sizes, etc. But there are loads of other benefits. It just takes a while to feel natural (just like Activities did at first).

One caveat, I always regret embedding fragments in my layouts. I can't give exact reasons here off the top of my head, but essentially you just lose some flexibility. Instead, I build a normal layout for each fragment, and add a placeholder view in the activity layout, create the fragment programmatically, and use transaction.replace() to add it to the layout. Perhaps because this is the main way I swap fragments in and out of that placeholder view, and prefer to just have a single way of doing things where possible.

Fragment vs. Custom View in Android

Fragment can be used in different scenarios but most used are:

  • wrapper around a view
  • headless fragment - i.e. no view => not very helpful in general but can be used
  • retainable fragment - can be any of above. By using Fragment.setRetainInstance(true) you can bypass Fragment.onDestroy(), i.e. can keep fragment data on configuration changes but fragment view structure is still destroyed/recreated
  • can be added to activity back stack, i.e. easy Back button previous state restore

There are cases where fragment are complete pain in the neck, then there are cases where they can achieve results quicker.

For some custom and more flexible situations fragments can get cluttered and managing them would be difficult. So dealing with views directly can be really handy and more helpful for some cases. But everything is based on requirements.

Note View has its own life cycle too and can store/recreate saved instance state. A little bit more work but it has the option too.

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