118

I often need the different parts of my applications to have their own special behavior and UI, and I don't know how fragments can help. In most cases, I think it is quicker to create 2 different activities (e.g., 1 for tablets and 1 for handsets), and to share the common behaviors and events in a third class.

So, keeping this in mind, why should I use fragments ?

nbro
  • 15,395
  • 32
  • 113
  • 196
Claudio Ferraro
  • 4,551
  • 6
  • 43
  • 78

5 Answers5

78

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Bob
  • 1,088
  • 1
  • 9
  • 15
  • 73
    Why use fragments when you can do the exact same thing with different parent layouts and different classes? Easier to have two parent layouts, one for list and the other for webview. I personaly think your answer is incorrect as you only stated what fragments are used for, not why you should use it instead of one activty hosting two classes. Infact, having one activity and host two classes that is easier as you do not need to deal with intents and parcelable interface to serialize your objects you wish to pass. you get direct class access – Jono May 02 '13 at 16:57
  • So, using fragments for a search form which is visible in more than one activities is recommended? – Muatik Aug 15 '14 at 08:35
  • OMG So THIS is how some apps now slide new "views" into view when i tap something? So to use a fragment, do we just have (for example) a main layout file and then use `` inside that file whereever we want to include a fragment? And maybe if we dont want a fragment to always be there either hide it and show it when needed or inject it when needed? – username Dec 26 '15 at 06:38
  • @jonney Because you want to code the list and the detail functionality once, and have Android decide, based on screen size, when to two put the the Fragment on a new or the same Activity. – Behnam Jul 28 '16 at 18:04
  • @Bob: "Bottom line: Fragments are two or more activities on the screen at the same time. And An Activity is ........" Could you please fill it up? It will help lot of newbies to understand better. – sofs1 Oct 15 '16 at 03:41
  • An Activity can contain one or more Fragments. Fragments are modular sections of an activity, usually meant to display UI. Above is what I learned from Android tutorials in Udacity. But your bottom line seems to be contradicting to this, but at the same time correct. I am confused. – sofs1 Oct 15 '16 at 03:45
64

The benefits I see when using fragments are:

  • Encapsulation of logic.
  • Better handle of the lifecycle of the fragment.
  • Reusable in other activities.

The drawbacks I see are:

  • More code(For example, instantiating a fragment manager, adding the fragment transaction, writing the callbacks of the fragment)
  • Communication between fragments and activities is harder. As @jonney said it, you would need to deal with a parcelable interface to serialize your objects you wish to pass.

So, when deciding to use a fragment, I would ask myself the following questions:

  • Is the lifecycle of the fragment different from the activity's lifecycle?

If the lifecycle is different, you get better handling of the lifecycle using a fragment. For example, if you want to destroy the fragment, but not the activity. Such is the case, when you have a pager adapter.

  • Is the fragment going to be used in several activities?

The user input events will be reusable if you use a fragment.

  • Is the amount of communication between the fragment and the activity small?

If you need to pass big objects to the fragment, you would need to deal with the code that serializes them. Also, if you need to communicate between fragment and activity, you would probably need to implement interfaces. This, in most cases, adds complexity to your codebase. It's not a difference maker, but a criteria to take into account.

Community
  • 1
  • 1
e3matheus
  • 2,112
  • 1
  • 20
  • 28
  • 1
    It's not only a programming matter. I simply think that doing an App is not only write the source code but to deal with some UI problems for Tablets which are different than the problems for handsets, and to be honest I really don't like too much how Fragments are supposed to solve the gap between screen sizes. Doing an App it's really not about to fill the empty spaces with some redundant pieces. Even from a programming point of View if my parts have troubles to communicate one which another I prefer to create a gateway class with common stuff instead of struggling with weak pipes. – Claudio Ferraro Dec 15 '13 at 00:47
  • about this sentence "Is the lifecycle of the fragment different from the activity's lifecycle?". I have had lotsa cases that the piece of view that is subject to be a separate view group has the same lifecycle. but I used fragment becuase i wanted to use it multiple places and at the same time i needed to be aware of lifecycle and do some logic depend on that. while if i used viewgroup i needed to inform the view group about lifecycle of activity calling some custom onResume method manually. – Amir Ziarati Jul 23 '17 at 07:57
20

Google advises you to ALWAYS use Fragments.

Why? It's simple:

In the simplest case, Fragments are used like containers of activities.

Why do you need this? Again, it's simple.

Android 4 (ICS) supports both Smartphones and Tablets. This means the SAME application will be running on a smartphone and a tablet and they are likely to be very different.

Tablets have big screens which will be empty or unused - unless you assign it properly.

That means- Putting two fragments on one activity like Contact List and Contact Info.

The smatphone will display contact List, and on a touch- display the contact's Info.

On a tablet, the user will still see the list and the info will be next to it.

2 fragments- on one screen....

Smart? yes... supposed to be back compatible down to Android 1.6......


#############################################################

O.K, Already Knew That? then - just try to understand the case solved:

A lot of things work that way- list & details, Menus and Sub-Menus, Info, Detailed Info and some more detailed info. You want a way to keep it natural and smooth for a tablet which you expect to preform that way, but can't expect smartphone to display it all like the tablet did...

Get it?

for more Information, check out this. I really think you just need to catch the concept....

zaxy78
  • 1,406
  • 3
  • 19
  • 32
  • Yes the concept is clear..But in simple interfaces where the different Activities doesn't have direct relation and every activity is simple a container of data ..are fragments really necessary ? Can I avoid that ? And from another perspective in any case the program should be adapted to run on different screen regardless from that fact you'll use fragments or not. – Claudio Ferraro Dec 22 '11 at 10:10
  • 1
    You are correct, you don't need Fragments to support multiple screen sizes. But they should make it easier. You should be able to instantiate the exact same fragment either as a whole-screen activity on a phone or as a partial screen on a tablet with only a few lines of code to tell the difference. Also, because fragments handle some of their own lifecycle, you have less to worry about. – Sparky Mar 22 '12 at 23:58
  • 2
    "Google advises you to ALWAYS use Fragments."? I don't agree with it. Personally I think it is useful only when the device is designe dot present one pane or two panes view, according to its size. – user1914692 Aug 08 '13 at 00:44
  • 2
    But no explanation of why bother when you can do the exact same thing in many cases with different view layouts. Like the op in don't see the need for fragments in many cases th ey are used. Overly complicated imo. T – RichieHH Aug 20 '14 at 23:06
9

Historically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. Instead the object must be serialized or a globally accessible reference made available.

By making each screen a separate Fragment, this data passing headache is completely avoided. Fragments always exist within the context of a given Activity and can always access that Activity. By storing the information of interest within the Activity, the Fragment for each screen can simply access the object reference through the Activity.

https://softwareengineering.stackexchange.com/questions/244771/why-use-android-fragments

Community
  • 1
  • 1
1

Fragment primary support more dynamic & Large UI Screen like Tablet.Because Tablet screen is much larger than normal Handset. There is more room to combine & Interchange UI Component.

Fragment allow such design without the need for such complex change in the View hierarchy.

By divide activity layout in fragment, we become able to modify activity's appearance at runtime