abdfahim
abdfahim

Reputation: 2553

Is using many fragments a bad practice?

I have an App which has, let say 15 different sections. I use a single Activity with a FrameLayout where I load 15 different Fragments using a NavigationDrawer. I also have child fragments under few parent Fragments where I load swipe Tab layout.

So, in short, I have lots of fragments in my App.

The issue is, if I add the fragments to the BackStack while adding to the FrameLayout, the fragments never gets destroyed as long as my App lives (only View gets destroyed, which is expected behavior by design). To make it worse, if the user keep hovering to different Fragments, the size of the BackStack keeps increasing which can result memory issues.

So, I started googling and found several threads in SO where some suggests against using Fragments at all. But if I want to design each section using its own Activity, I have to add NavDrawer to each activity (or at least extend those activity to a base activity) which I am not sure if prudent.

That leaves to the question, is it a good design to have lots of fragments in a single activity? If it's fine, should I add the fragments to the BackStack? If I should, what about memory issues? And finally, has anybody tried NavigationDrawer across different activities? Is it efficient?

My apology for a series of questions.

Edit: Based on the responses so far, I want to clarify that, I know it is sort of generic question, and can result different opinion-based responses. So, I want to make it clear that, I am not looking for any decisive answer (becuase there might not be any), rather I wanted to open a discussion to hear from different perspectives.

Upvotes: 4

Views: 1529

Answers (1)

Vaiden
Vaiden

Reputation: 16122

This is a very general question.

Using Fragments is a well tested Android pattern. They provide you with a handy, small scale View Controller with a fully managed lifecycle. That's neat.

But Fragments are not always the right tool for the job.

My rule of thumb is: I use Fragments for whenever I need to manage a complex View's lifecycle, for Fragment animations and whenever I need an Activity which is not full screen.

If you find yourself having a lot of Fragments, then ask yourself what can you abstract or generalise. For instance: most list Fragments look and perform the same, and each row should probably not be implemented in a Fragment of its own.

The backstack is, IMHO, a UX tool. It needs to be managed in a way that makes sense in your app's business logic. It's a tool for allowing your user to naturally navigate your app. So pushing more than 4 or 5 Fragments in the stack dos not make sense, as you should not expect the user to remember 5 navigational decisions by heart. If you find yourself in a large backstack situation, you probably need to rethink your UX design.

Upvotes: 1

Related Questions