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

6

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?

Testis answered 23/12, 2011 at 15:25 Comment(2)
Fragments don't have to have an UI, they can just be reusable behavior. A View would be redundant in that case.Etymologize
I've answered this in another question. See https://mcmap.net/q/211845/-why-use-fragments-duplicate T;dr - sometimes fragments allow you to create more reusable components than relying on custom view implementation. see the link for why.Cammi
C
176

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://mcmap.net/q/211846/-android-fragments-vs-compound-controls

Crichton answered 5/4, 2013 at 1:7 Comment(7)
Very good answer. I just wanted to add that fragments can be nested since 4.2 or support library rev 11.Donnie
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.Crichton
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!Testis
Want to +1 this answer, but doing that would ruin the current score. Besides, 70 is not my favorite number.Tirza
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 easyBrewhouse
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." developer.android.com/guide/components/fragments.html#DesignOrmiston
Unless you want to implement a back stack of your own.Escargot
B
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.

Barolet answered 23/12, 2011 at 15:52 Comment(1)
Thanks, this was definitely helpful. I think I will stick with views and make my own 'back stack' to make them reusable.Testis
D
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.

Disdainful answered 23/12, 2011 at 15:55 Comment(1)
I have read all the documentation, however I was looking for something that better explains their benefit, such as for tablets or the backstackTestis
M
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.

Mallett answered 18/1, 2013 at 15:38 Comment(0)
M
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)

Mulder answered 5/11, 2013 at 1:41 Comment(0)
C
-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.

Congruent answered 24/7, 2015 at 19:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.