103

When developing for Android, you can set your target (or minimum) sdk to 4 (API 1.6) and add the android compatibility package (v4) to add support for Fragments. Yesterday I did this and successfully implemented Fragments to visualize data from a custom class.

My question is this: what is the benefit for using Fragments as opposed to simply getting a View from a custom object, and still supporting API 1.5?

For example, say I have the class Foo.java:

public class Foo extends Fragment {

    /** Title of the Foo object*/
    private String title;
    /** A description of Foo */
    private String message;

    /** Create a new Foo
     * @param title
     * @param message */
    public Foo(String title, String message) {
        this.title = title;
        this.message = message;
    }//Foo

    /** Retrieves the View to display (supports API 1.5. To use,
     * remove 'extends Fragment' from the class statement, along with
     * the method {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}) 
     * @param context Used for retrieving the inflater */
    public View getView(Context context) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.foo, null);
        TextView t = (TextView) v.findViewById(R.id.title);
        t.setText(this.title);
        TextView m = (TextView) v.findViewById(R.id.message);
        m.setText(this.message);
        return v;
    }//getView 

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }
        View v = inflater.inflate(R.layout.foo, null);
        TextView t = (TextView) v.findViewById(R.id.title);
        t.setText(this.title);
        TextView m = (TextView) v.findViewById(R.id.message);
        m.setText(this.message);
        return v;
    }//onCreateView

}//Foo

Both methods are very simple to create and to work with in an Activity that, say, has a List<Foo> to display (for example, programmatically adding each to a ScrollView), so are Fragments really all that useful, or are they just an over-glorified simplification of getting a View, such as through the code above?

Phil
  • 34,061
  • 21
  • 117
  • 154
  • 2
    Fragments don't have to have an UI, they can just be reusable behavior. A View would be redundant in that case. – Philipp Reichart Dec 23 '11 at 15:57
  • I've answered this in another question. See http://stackoverflow.com/a/14912608/909956 T;dr - sometimes fragments allow you to create more reusable components than relying on custom view implementation. see the link for why. – numan salati Feb 16 '13 at 16:52

6 Answers6

173

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

Community
  • 1
  • 1
Henry
  • 2,610
  • 2
  • 17
  • 23
  • 14
    Very good answer. I just wanted to add that fragments can be nested since 4.2 or support library rev 11. – kar Jul 17 '13 at 08:26
  • 2
    Thanks @Karlo for the update. I didn't think it was conceptually possible, but they worked around it by using a private FragmentManager through getChildFragmentManager(). Oh, and it is API 17, not 11, and available through the Support Library. – Henry Jul 24 '13 at 08:29
  • 2
    I just was looking at this question again, and my experience has changed too. This is an answer that provides a good understanding of both benefits and drawbacks, and is very helpful. Thanks! – Phil Feb 21 '14 at 16:03
  • 2
    Want to +1 this answer, but doing that would ruin the current score. Besides, 70 is not my favorite number. – Behnam Nov 12 '14 at 06:24
  • 1
    for last year, I was also thinking that Fragments don't provide any extra ordinary feature, but I experienced that after clicking back on activity I was loosing all images downloaded in that, so had to add cache implementation, now I'm thinking using fragments it may be very easy – Shirish Herwade Feb 09 '15 at 13:53
  • From the official document, at "Design Philosophy" Section, "By dividing the layout of an activity into fragments, you become able to modify the activity's appearance at runtime and preserve those changes in a back stack that's managed by the activity." http://developer.android.com/guide/components/fragments.html#Design – Sam003 Jul 14 '15 at 20:46
  • Unless you want to implement a back stack of your own. – dramzy Nov 19 '15 at 20:56
27

I'd say Fragments are useful in two scenarios: if you split up views on some devices/orientations and show them in two activities and show all the content in one on other devices. That would be a use case if you go on a tablet or maybe even in landscape mode on a phone: e.g. you show the list of items and the details on one screen. on a phone or in portrait mode you just show one part.

Another use case are reusable views. So if you have some views that are visible on different activities and also perform some actions you could put this behaviour into a fragment and then reuse it. Obviously you could probably do that with custom widgets too.

I wouldn't see any reason for using Fragments for every View and I guess it would just be an overhead. I'm only using them in the first use case and I'd say here it is a simplification.

Maria Neumayer
  • 3,299
  • 3
  • 25
  • 43
  • Thanks, this was definitely helpful. I think I will stick with views and make my own 'back stack' to make them reusable. – Phil Dec 27 '11 at 02:43
3
  1. Scenario Activity Split screen - We have One Layout and one activity which handle left right screen part
  2. Scenario FragmentActivity we have One layout for Main screen, one for left one for right

Scenario one is good if you have simple application.

Scenario two is good if you want to have Multiple Fragments and multiple FragmentActivities and you can combine each of those. Also you can make interaction between fragments.

I have split screen Fragmentactivity i can call it with 'Intent Extras' and tell to fragmentActivity which fragment are to be loaded. Fragments are good because they are not in manifest so you could make reusable fragments and FragmentActvity.

But it make your project larger. But if you make large project you can save many. Because you can use same Fragments or same Fragment activity.

And i thing that this fragments come little late so you must try to think in new way. Maybe just try to convert your activity to FragmentActivity. Later try to find reusable code and make Fragment from it.

Its usefull but i dont know how right now. But i have some ideas.

This is always problem. Android Team made somethink and nobody know what is good for. Because we are hardly learn like it was and here it comes some new things.

In my opinion it is good but not for reason that google tell us.

Mertuarez
  • 861
  • 7
  • 24
3

Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet's screen is much larger than that of a handset, there's more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able to modify the activity's appearance at runtime and preserve those changes in a back stack that's managed by the activity.

Here you can read more.

Yury
  • 19,498
  • 7
  • 52
  • 79
  • I have read all the documentation, however I was looking for something that better explains their benefit, such as for tablets or the backstack – Phil Dec 27 '11 at 02:41
0

Add one case when using Fragment or Activity over CustomView:

When you are using CursorLoader to observe certain views, ListView or TextView and want to update their display value whenever your ContentProvider's data updates at back end(most common case you have a service which updates your local database by polling data from remote database/cloud periodically)

macio.Jun
  • 8,823
  • 1
  • 42
  • 40
-2

One big thing all the above comments don't mention is that a fragment remains resident in memory even if Android kills the activity and restarts it when you do something like change the orientation of your device. This is done for performance reasons but can also lead to unexpected results if you were expecting fragments to be destroyed only to find that they are getting recreated out of nowhere.

AndroidDev
  • 20,063
  • 26
  • 131
  • 216