CodyBugstein CodyBugstein - 28 days ago 7
Android Question

Is there any point of an Activity with one fragment?

All the reasons I can find for using Fragments in Android activities have to do with having the ability to display multiple classes/view in the same screen, encapsulating multiple logical components, etc.

Considering all this, it seems, fragments are only actually useful when you employ the use of many of them.

Is that so? Is there ever a point of using just one fragment in an activity?

I ask now because I saw an option on Android Studio to do just that, and I am wondering what the point is.

Android Studio New Activity with Fragment

Answer

Out of my personal opinion, I would say yes.

For the following reasons:

  • Creating a Fragment is hardly any extra work and has a lot of benefits.
  • Fragments can easily be reused somewhere else (possibly another Activity that has more fragments, furthermore, Fragments do not necessarily need to use up the full screen).
  • Activity transitions are more expensive, Fragment transitions are more sophisticated.
  • Fragment animation framework is better.
  • I always like to keep the number of Activities to a minimum.
  • Code is cleaner / better structured / easier to maintain.

According to google coding guidelines, it is best practice to create as few Activities as possible, and create multiple Fragments instead that are switched inside an Activity.