Home > Software design >  Activity vs Fragment
Activity vs Fragment

Time:10-09

I am learning android from two resources one from video and one from book (android developer resources ). Both show how to have multiple views in a different ways. Video one used activity and intent book used fragments. What is the best practice fragment/activity?When to use Activity and when to use Fragment.

CodePudding user response:

You will most likely hear things like

You can have an Activity without a Fragment but you cannot have a Fragment without Activity

You can have multiple Fragments under a single Activity

You can use Fragments to have multiple sections in a single screen

Fragments has its own lifecycle

So I'd give my personal thought and a little bit of scenario based on my own experience on how I would decide which to use based on a given scenario.

Consider a Registration Form where I'm required to create 3 screen features of which contains Basic Personal Info, Financial Information and Online Mailing Information, in this case I would use multiple Fragments under 1 hosting Activity named RegistrationActivity.

Now consider same application where I'm required to create a User Setting Screen it wouldn't make sense if I create another Fragment under that same Activity right?, so that would be a separate context and everything about it will go to another Activity named SettingsActivity

There are more technical things under the hood, but most of the time you will decide which to use based on the use-case you are dealing with.

There is also an up to date architecture namely Modular design where each closely related components are grouped inside a module library, majority of such project will fall under the feature category where most of the time if not all, have single Activity hosting multiple fragments. And going back to my scenario it would be like a Registration Module

Hope it make sense.

Have a look at another similar post Why fragments, and when to use fragments instead of activities?

  • Related