161

I am thinking of implementing one screen with Activity and all other sreens with Fragments and managing all the fragments thru the activity.

Is it a good idea? and my answer is NO but still I want to know more clearly about this thought.

What are the pros and cons of the idea?

Note:

Please don't give me the link for fragment and activity.

EDIT:

Here is something over Fragments and activity:

Pros:

  1. Fragments are meant to be used with activities as a sub activity.
  2. Fragments are not the replacement for activities.
  3. Fragments are meant for reusability(Need to know in what way reusability can be achieved.).
  4. Fragments are the best way to write code to support both tablets and phones.

Cons:

  1. We need to implement the interface to get the data from fragments.
  2. For dialog we have to go a long way to show it.

Why should we use fragments if we are not considering tablets? What is the starting time difference between activity and fragment?

8
  • Can you elaborate on why you think the answer is no? I happen to disagree, but it's easier to address concerns you might have about that approach if we know what those concerns are. Sep 4, 2012 at 22:37
  • 1
    @AlexanderLucas The answer I gave no because doing so makes your code less modular, increases complexity. Sep 5, 2012 at 14:37
  • @Ski You are concentrating more on getting your answer accepted, plz concentrate on what is being asked and what should be best answer which you can provide. Sep 5, 2012 at 14:43
  • 3
    For anyone who finds this, I stopped the refactor because things got really complicated really quick.
    – theblang
    Jun 11, 2014 at 21:57
  • 21
    This is a good question and should not have been closed. Jul 27, 2015 at 21:02

8 Answers 8

95
+25

It depends on the app you are creating. I've created several apps using both approaches and can't say one way is always better than the other. The latest app I created I used the single Activity approach and a Facebook style navigation. When selecting items from the navigation list I update a single Fragment container to display that section.

That said, having a single Activity also introduces a lot of complexities. Let's say you have an edit form, and for some of the items the user needs to select, or create, requires them to go to a new screen. With activities we'd just call the new screen with startActivityForResult but with Fragments there is no such thing so you end up storing the value on the Activity and having the main edit fragment check the Activity to see if data has been selected and should be displayed to the user.

What Aravind says about being stuck to a single Activity type is also true but not really that limiting. Your activity would be a FragmentActivity and as long as you don't need a MapView then there are no real limitations. If you do want to display maps though, it can be done, but you'll need to either modify the Android Compatibility Library to have FragmentActivity extend MapActivity or use the the publicly available android-support-v4-googlemaps.

Ultimately most the devs I know that went the one Activity route have gone back to multiple Activities to simplify their code. UI wise, on a tablet, you are some times stuck using a single Activity just to achieve what ever crazy interaction your designers come up with :)

-- EDIT --

Google has finally released MapFragment to the compatibility library so you no longer have to use the android-support-v4-googlemaps hack. Read about the update here: Google Maps Android API v2

-- EDIT 2 --

I just read this great post about the modern (2017) state of fragments and remembered this old answer. Thought I would share: Fragments: The Solution to All of Android's Problems

3
  • 6
    There's settargetfragment and you could handle the activity like startforresult procedure.
    – Lalith B
    Oct 24, 2013 at 18:26
  • 1
    In my opinion activities exist just because it's the old system. Fragment didn't exist before. There's really nothing that activities can and fragments can't, besides formalities. I could even imagine that at some point activities are removed and everything is a fragment.
    – User
    Dec 30, 2013 at 5:04
  • 1
    Summarising the cons of fragments-only you give, there aren't really any. startActivityForResult as Lalith B says has a counterpart, and maps is also not an issue. Besides of that everything (saving state, etc.) can be handled with the lifecycle methods of the fragment.
    – User
    Dec 30, 2013 at 5:08
85

I'm about to finish a project(5 months in development), that has 1 activity, and 17 fragments, all full screen. This is my second fragment based project(previous was 4 months).

Pros

  • The main activity is 700 lines of code, just nicely managing the order of the fragments navigation.
  • Each fragment is nicely separated into it's own class, and is relatively small (~couple hundred lines of ui stuff).
  • Management can say, "hey, how about we switch the order of those screens", and I can do it very easily, as those fragments don't depend on each other, they all communicate through the activity. I don't have to dig through individual activities, to find where they call each other.
  • my app is very graphics heavy, and would never work as 1 screen 1 activity. All those sub activities in the memory, would make the app run out of memory all the time, so I would have to finish() all non visible activities, and make the same control logic for navigation, as I would do with fragments. Might as well do it with fragments just because of this.
  • if we ever do a tablet app, we will have an easier time re-factoring stuff, because everything is nicely separated already.

Cons

  • you have to learn, how to use fragments
15
  • 1
    wasn't sure about having too many fragment and only now activity... any issues on production, and the blame is on you!! :)
    – Shahar
    Feb 25, 2014 at 10:44
  • 1
    @Dinash don't let the os restart your activity. handle the orientation change yourself. read more here: stackoverflow.com/questions/5913130/…
    – Tamas
    May 5, 2014 at 11:10
  • 1
    @Tamas Did you have any multi-fragment screens (ex. master-detail) and if so how did you handle that?
    – theblang
    May 13, 2014 at 18:17
  • 7
    @Tamas This approach is heavily anti android. You end up with GOD class. Android system is designed to work with activities - e.g. you don't have a nice way to handle Toolbars within multiple fragments. You don't have start fragment for result and many more don't haves. That means you have to rewrite the whole logic that is already there. What about Local broadcast receivers, services and other android components. In order to start a service you have to do the following: getActivity() != null ... this is really ugly. Also communication between fragments is very weird if you have a lot of fr.
    – Teodor
    Mar 31, 2016 at 12:53
  • 11
    700 lines!!!! "nicely"???? Classes are free.
    – beplaya
    Dec 18, 2016 at 18:34
16

First, whatever you do, make sure you have a modular design using model, view, presenter that is not highly dependent on an Activity or a Fragment.

What do Activities and Fragments really provide?

  1. Life cycle events and backstack
  2. Context and resources

Therefore, use them for that, ONLY. They have enough responsibility, don't over complicate them. I would argue that even intantiating a TextView in an Activity or Fragment is bad practice. There is a reason methods like public View findViewById (int id) are PUBLIC.

Now the question gets simpler: Do I need multiple, independent life cycle events and backstacks? If you think yeah maybe, use fragments. If you think never ever, don't use fragments.

In the end, you could make your own backstack and life cycles. But, why recreate the wheel?

3
  • Hm... the connection between instantiating a view being a bad practice and findViewById() public is unclear. While I agree about instantiation of views, I also consider calling findViewById from other class (e.g. the activity hosting a fragment calls it on the fragment) a bad practice. Don't really know why this is public, since, at least in the cases I can think of, this results in messy code and not modular design.
    – User
    Dec 30, 2013 at 5:21
  • IMHO: If you pass an actvity into your view and presenter (calling the 2 combined a "module"), you enble reuse of that module withn other activties. Ifit helps, itmay be best to pass the activity as an intrfce that exposesonly necsary thngs. If u hate finding views outside ofthe actvity, then you could inject allthe views, via that intrface, into the pres./view. main point is that I belive Android coding should be done outsde the concept of Actvities and Frags, sothat swtching btwn the 2 is easy.Then,it becomes clear wht is bst and you're not stuck with one or the other inside a web of code.
    – beplaya
    Jan 23, 2014 at 2:49
  • 3
    Let go of the MVP, you'll be better off without it w.r.t. Android. You can spend a lot of time trying to fit a certain shape block through a hole that's a different shape, sure it's a challenge but there's probably functional requirements you'd be wiser spending time on.
    – straya
    Jul 22, 2015 at 10:51
12

Pros

You could control your fragments from a single activity, beacause all fragments are independent of each other. The fragments have a lifecycle (onPause, onCreate, onStart...) of their own. By having a lifecycle, fragments can respond independently to events, save their state through onSaveInstanceState, and be brought back (i.e. such as when resuming after an incoming call or when the user clicks the back button).

Cons

  1. Create complexity in your code of activity.
  2. You have to manage the order of the fragments.

Never the less, it is quite a good idea, as if you need to create an app, where you want to show several views. By this idea, you'll be able to view several fragments in a single view..

2

It depends on the design layout of your app. Suppose if your using Tabs in ActionBar in the design layout then in the Single Activity of the app one can have fragments being changed on Tab click. So now you have an Activity and say suppose three Tabs in the ActionBar and the view for the tabs being provided by the Fragments, which makes it easy to manage plus is feasible also. So, it all depends on the design scheme of your app and how you take the decision to build for it.

1

Pros:

  • Can be used to create a single interface usable by multiple screen sizes and orientations via xml layouts.

Cons:

  • Requires more complex code in your activity.

I believe it's a good idea, because using different xml layouts based on the current screen size and orientation can make the app more usable and reduce the need to release multiple versions of your app if you plan on releasing your app for both phones and tablets. If your app will never be used by both tablets and phones, it's probably not worth the trouble.

2
  • For orientation it is not necessary to use different xml-based layouts. Sep 5, 2012 at 14:32
  • @VineetShukla true, but it is an option, just like using different xml layouts based on screen size. For instance, my Android phone's home screen has a different layout when I view it in landscape orientation versus portrait.
    – Ski
    Sep 5, 2012 at 18:25
0

I'm a proponent of deferring all view inflation to fragments to provide better flexibility. For example having a single landing activity for a tablet which aggregates multiple fragments and reusing the same fragments on a phone to show one screen per fragment. However in the phone implementation I'd have a separate activity for each screen. The activities would not have too much code as they would immediately defer to their fragment counterpart for view inflation.

I think it's a bad idea for the phone implementation to have to change to a single landing activity when tabs or a slide out menu is introduced since the tab or menu navigation just results in a completely new screen.

1
  • "I think it's a bad idea for the phone implementation to have to change to a single landing activity when tabs or a slide out menu is introduced since the tab or menu navigation just results in a completely new screen." -> It's not understandable what exactly you mean, but, neither tabs or side menu are a problem in a single-activty app (tablet/phone).
    – User
    Dec 30, 2013 at 5:27
-1

The most important reason I would give for not using the single activity approach is so that the activity lifecycle can be taken advantage of. Activities contain contextual behavior of a certain portion of the application and fragments supplement that behavior. Having the ability to take advantage of the overridable steps in the activity lifecycle helps to separate one activity's behavior from another with methods such as onPause and onResume. This lifecycle also allows you return to previous context. With the single activity approach, once you leave a fragment you have to create an mechanism to return to it.

1
  • 4
    I don't believe this is true. From the Fragment lifecycle documentation (developer.android.com/guide/components/fragments.html#Lifecycle) : "The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the fragment, such that each lifecycle callback for the activity results in a similar callback for each fragment. For example, when the activity receives onPause(), each fragment in the activity receives onPause()."
    – Ski
    Aug 31, 2012 at 17:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.