When to use Fragments vs Activities?

Technology CommunityCategory: AndroidWhen to use Fragments vs Activities?
VietMX Staff asked 3 years ago

Activities are designed to represent a single screen of my application, while Fragments are designed to be reusable UI layouts with logic embedded inside of them.

Google advises you to always use Fragments. In the simplest case, Fragments are used like containers of activities.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.

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