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

AndroidAndroid FragmentsAndroid ViewAndroid LifecycleSoftware Design

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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.

Solution 3 - Android

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

Solution 4 - Android

  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.

Solution 5 - Android

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)

Solution 6 - Android

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhilView Question on Stackoverflow
Solution 1 - AndroidHenryView Answer on Stackoverflow
Solution 2 - AndroidMaria NeumayerView Answer on Stackoverflow
Solution 3 - AndroidYuryView Answer on Stackoverflow
Solution 4 - AndroidMertuarezView Answer on Stackoverflow
Solution 5 - Androidmacio.JunView Answer on Stackoverflow
Solution 6 - AndroidJohannView Answer on Stackoverflow