Allan Macmillan
Allan Macmillan

Reputation: 1491

One Fragment per Activity

I know this question will probably get closed very quickly as its largely opinion based but I have little experience using Android and could do with some guidance.

I have built an App and every Activity only hosts one fragment, and I have around 10 activities overall, meaning I also have 10 fragments.

Is it bad practice to just have one fragment being hosted by each activity as I know an activity can host multiple fragments? Should I use one or two activities that host multiple fragments or is the way I currently do it okay?

Upvotes: 0

Views: 948

Answers (2)

brwngrldev
brwngrldev

Reputation: 3704

From the Android Docs: http://developer.android.com/guide/components/fragments.html

You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

So if you are reusing components in the various activities, then it may be advisable to create a few fragments that can swapped in and out, instead of having everything in so many activities. Also, if you plan on supporting multiple screens/devices it tends to be easier by having fewer activities and making use of reusable fragments.

Upvotes: 0

waqaslam
waqaslam

Reputation: 68187

The purpose of Fragment is to use/reuse an area/portion inside an Activity. In your current design, you don't really need fragments at all, because whatever being shown on fragment can directly be shown in your 10 activities.

However, if you want, you may use single Activity and host a fragment (out of your 10 fragments) depending on the selection/criteria.

Upvotes: 1

Related Questions