Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 349
CodyBugstein Avatar asked Oct 06 '14 09:10

CodyBugstein


People also ask

Does an activity need a fragment?

Fragment cannot be used without an Activity. While Using fragments in the project, the project structure will be good and we can handle it easily. Lifecycle methods are hosted by OS. The activity has its own life cycle.

What is the purpose of using fragments in an activity?

Fragments introduce modularity and reusability into your activity's UI by allowing you to divide the UI into discrete chunks. Activities are an ideal place to put global elements around your app's user interface, such as a navigation drawer.

Can you use a fragment in more than one activity?

You can use a Fragment in more than one Activity . One Activity can have multiple fragments. After you define a Fragment in a Kotlin class, the fragment is automatically added to the activity_main.

What is a fragment and why would you use one?

Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up.


1 Answers

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.

like image 96
Philipp Jahoda Avatar answered Sep 21 '22 00:09

Philipp Jahoda