CodyBugstein
CodyBugstein

Reputation: 23312

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

Upvotes: 11

Views: 2124

Answers (3)

Philipp Jahoda
Philipp Jahoda

Reputation: 51411

Out of my personal opinion, I would say yes.

For the following reasons:

  • Assuming you are familiar with Fragments, creating a Fragment is hardly any extra work plus has the following 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.
  • The Fragment animation framework is better (in terms of usability and performance).
  • I always like to keep the number of Activities to a minimum which keeps the AndroidManifest.xml short and clean.
  • UI separated into Fragments leads to cleaner code structure and easier code maintenance.

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.

Upvotes: 5

Elsanty
Elsanty

Reputation: 148

Well it depends, if you are going to use that fragment in another activity yea, you have a "point" and maybe in a future you can reuse it on another activity, but in the case for example of a splash screen well, it don't have a point. All depend in the uses you want to give to your application.

Upvotes: 1

Mehul Joisar
Mehul Joisar

Reputation: 15358

Pros:

-> reusable piece of code

  • easy to utilize it again in any module
  • easy to debug

-> handles orientation changes better than activity using setRetainInstance(true)

-> great help when scale the app in future for multipane layouts or multi-screen support

Cons:

-> little overhead and time consuming if you are not familiar with fragments

Upvotes: 0

Related Questions