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