Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
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:
Fragments are meant to be used with activities as a sub activity.
Fragments are not the replacement for activities.
Fragments are meant for reusability(Need to know in what way reusability can be achieved.).
Fragments are the best way to write code to support both tablets and phones.
Cons:
We need to implement the interface to get the data from fragments.
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?
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
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
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?
Life cycle events and backstack
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?
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
Create complexity in your code of activity.
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..
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.
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.
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.
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.
Related
I know that Activities are designed to represent a single screen of my application, while Fragments are designed to be reusable UI layouts with logic embedded inside of them.
Until not long ago, I developed an application as it said that they should be developed.
I created an Activity to represent a screen of my application and used Fragments for ViewPager or Google Maps. I rarely created a ListFragment or other UI that can be reused several times.
Recently I stumbled on a project that contains only 2 Activities one is a SettingsActivity and other one is the MainActivity. The layout of the MainActivity is populated with many hidden full screen UI fragments and only one is shown. In the Activity logic there are many FragmentTransitions between the different screens of the application.
What I like about this approach is that because the application uses an ActionBar, it stays intact and does not move with the screen switching animation, which is what happens with Activity switching. This give a more fluent feel to those screen transitions.
So I guess what I'm asking is to share your current development manner regarding this topic, I know it might look like an opinion based question at first look but I look at it as an Android design and architecture question... Not really an opinion based one.
UPDATE (01.05.2014): Following this presentation by Eric Burke from Square, (which I have to say is a great presentation with a lot of useful tools for android developers. And I am not related in any way to Square)
http://www.infoq.com/presentations/Android-Design/
From my personal experience over the past few months, I found that the best way to construct my applications is to create groups of fragments that come to represent a flow in the application and present all those fragments in one Activity. So basically you will have the same number of Activities in your application as the number of flows.
That way the action bar stays intact on all the flow's screens, but is being recreated on changing a flow which makes a lot of sense. As Eric Burke states and as I have come to realize as well, the philosophy of using as few Activities as possible is not applicable for all situations because it creates a mess in what he calls the "God" activity.
Experts will tell you: "When I see the UI, I will know whether to use an Activity or a Fragment". In the beginning this will not have any sense, but in time, you will actually be able to tell if you need Fragment or not.
There is a good practice I found very helpful for me. It occurred to me while I was trying to explain something to my daughter.
Namely, imagine a box which represents a screen. Can you load another screen in this box? If you use a new box, will you have to copy multiple items from the 1st box? If the answer is Yes, then you should use Fragments, because the root Activity can hold all duplicated elements to save you time in creating them, and you can simply replace parts of the box.
But don't forget that you always need a box container (Activity) or your parts will be dispersed. So one box with parts inside.
Take care not to misuse the box. Android UX experts advise (you can find them on YouTube) when we should explicitly load another Activity, instead to use a Fragment (like when we deal with the Navigation Drawer which has categories). Once you feel comfortable with Fragments, you can watch all their videos. Even more they are mandatory material.
Can you right now look at your UI and figure out if you need an Activity or a Fragment? Did you get a new perspective? I think you did.
My philosophy is this:
Create an activity only if it's absolutely absolutely required. With the back stack made available for committing bunch of fragment transactions, I try to create as few activities in my app as possible. Also, communicating between various fragments is much easier than sending data back and forth between activities.
Activity transitions are expensive, right? At least I believe so - since the old activity has to be destroyed/paused/stopped, pushed onto the stack, and then the new activity has to be created/started/resumed.
It's just my philosophy since fragments were introduced.
Well, according to Google's lectures (maybe here, I don't remember) , you should consider using Fragments whenever it's possible, as it makes your code easier to maintain and control.
However, I think that on some cases it can get too complex, as the activity that hosts the fragments need to navigate/communicate between them.
I think you should decide by yourself what's best for you. It's usually not that hard to convert an activity to a fragment and vice versa.
I've created a post about this dillema here, if you wish to read some further.
Since Jetpack, Single-Activity app is the preferred architecture. Usefull especially with the Navigation Architecture Component.
source
Why I prefer Fragment over Activity in ALL CASES.
Activity is expensive. In Fragment, views and property states are separated - whenever a fragment is in backstack, its views will be destroyed. So you can stack much more Fragments than Activity.
Backstack manipulation. With FragmentManager, it's easy to clear all the Fragments, insert more than on Fragments and etcs. But for Activity, it will be a nightmare to manipulate those stuff.
A much predictable lifecycle. As long as the host Activity is not recycled. the Fragments in the backstack will not be recycled. So it's possible to use FragmentManager::getFragments() to find specific Fragment (not encouraged).
In my opinion it's not really relevant. The key factor to consider is
how often are you gonna reuse parts of the UI (menus for example),
is the app also for tablets?
The main use of fragments is to build multipane activities, which makes it perfect for Tablet/Phone responsive apps.
Don't forget that an activity is application's block/component which can be shared and started through Intent! So each activity in your application should solve only one kind of task. If you have only one task in your application then I think you need only one activity and many fragments if needed. Of course you can reuse fragments in future activities which solve another tasks. This approach will be clear and logical separation of tasks. And you no need to maintain one activity with different intent filter parameters for different sets of fragments. You define tasks at the design stage of the development process based on requirements.
There's more to this than you realize, you have to remember than an activity that is launched does not implicitly destroy the calling activity. Sure, you can set it up such that your user clicks a button to go to a page, you start that page's activity and destroy the current one. This causes a lot of overhead. The best guide I can give you is:
** Start a new activity only if it makes sense to have the main activity and this one open at the same time (think of multiple windows).
A great example of when it makes sense to have multiple activities is Google Drive. The main activity provides a file explorer. When a file is opened, a new activity is launched to view that file. You can press the recent apps button which will allow you to go back to the browser without closing the opened document, then perhaps even open another document in parallel to the first.
Thing I did: Using less fragment when possible. Unfortunately, it's possible in almost case. So, I end up with a lot of fragments and a little of activities.
Some drawbacks I've realized:
ActionBar & Menu: When 2 fragment has different title, menu, that
will hard to handle. Ex: when adding new fragment, you can change action bar title, but when pop it from backstack there is no way to restore the old title. You may need an Toolbar in every fragment for this case, but let believe me, that will spend you more time.
When we need startForResult, activity has but fragment hasn't.
Don't have transition animation by default
My solution for this is using an Activity to wrap a fragment inside. So we have separate action bar, menu, startActivityForResult, animation,...
The one big advantage of a fragment over activity is that , the code which is used for fragment can be used for different activities. So, it provides re-usability of code in application development.
use one activity per application to provide base for fragment
use fragment for screen ,
fragments are lite weight as compared to activites
fragments are reusable
fragments are better suited for app which support both phone & tablet
You are free to use one of those.
Basically, you have to evaluate which is the best one to your app. Think about how you will manage the business flow and how to store/manage data preferences.
Think about, how Fragments store garbage data. When you implement the fragment, you have a activity root to fill with fragment(s). So, if your trying to implement a lot of activities with too much fragments, you have to consider performance on your app, coz you're manipulating (coarsely speaks) two context lifecycle, remember the complexity.
Remember: should I use fragments? Why shouldn't I?
regards.
I use Fragments for better user experience. For example if you have a Button and you want to run let's say a webservice when you click it, I attach a Fragment to the parent Activity.
if (id == R.id.forecast) {
ForecastFragment forecastFragment = new ForecastFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_content, forecastFragment);
ft.addToBackStack("backstack");
forecastFragment.setArguments(b);
ft.commit();
}
In that way the user won't have to move in another activity.
And secondly I prefer Fragments because you can handle them easily during rotation.
It depends what you want to build really. For example the navigation drawer uses fragments. Tabs use fragments as well. Another good implementation,is where you have a listview. When you rotate the phone and click a row the activity is shown in the remaining half of the screen. Personally,I use fragments and fragment dialogs,as it is more professional. Plus they are handled easier in rotation.
Almost always use fragments. If you know that the app you are building will remain very small, the extra effort of using fragments may not be worth it, so they can be left out. For larger apps, the complexity introduced is offset by the flexibility fragments provide, making it easier to justify having them in the project.
Some people are very opposed to the additional complexity involved with fragments and their lifecycles, so they never use them in their projects. An issue with this approach is that there are several APIs in Android that rely on fragments, such as ViewPager and the Jetpack Navigation library. If you need to use these options in your app, then you must use fragments to get their benefits.
Excerpt From: Kristin Marsicano. “Android Programming: The Big Nerd Ranch Guide, 4th Edition.” Apple Books.
Some wrong ideas:
Always put an activity in your app and handle different screens with fragments.
Write the UI code directly in the activity.
Handle navigating between screens (I don't mean tabs, I mean for example full-screen views) by fragments.
Activities can be replaced by fragments.
Here is the thing!
Fragments are designed to implement reusable parts of UI and use them in any part of the app that is needed. They are not designed for substituting activities.
When we must use each of them?
When we have an independent screen in which there are some different UI parts (tabs, expandable screens, partial screens, etc...) we should use an activity with some fragments to implement and handle different UI parts separately in the same screen.
Each independent part of the application is actually a component that is conceptually different from other parts and it needs to have an independent activity. For example, the login part may contain some different scenarios like using username-password or using fingerprint. Each scenario can be implemented by a fragment and all login-related fragments should be handled by LoginActivity. But for example, the part of the orders in the application doesn't have a conceptual relationship with login, so it must have a different activity and of course, it may contain some fragments like OrdersFragment, SubmitNewOrderFragment, and etc that all of them must be managed by OrdersActivity.
Do not implement a UI directly in an activity. Always implement UI in fragments and add those fragments in the activity even if there is only one fragment in that activity. It helps you to have more reusable code and change UIs easier.
Never use fragments to navigate infinitely in the application even if you force the user to have a limited number of fragments in the back stack. The fact is that when you add a new fragment into the back stack and remove it, it will not be removed from the memory unless the parent activity gets destroyed and it is only not visible. So when you are using fragment manager back stack, by navigating multiple times between fragments in the same activity (especially in the case of you create a new fragment on each navigation and put them into the back stack) you will get an OutOfMemoryException in the application.
I hope it to be helpful.
This question needs to be reevaluated since Jetpack Compose has reached stable.
Jetpack Compose is Android’s recommended modern toolkit for building
native UI.
from https://developer.android.com/jetpack/compose
The typical jetpack-compose architecture is:
Single Activity, multiple composables, and glued together by jetpack navigation.
Note there's no (need for) Fragments anymore.
See Now in Android for a sample.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Why would someone creates activities as opposed to one activity with many fragments? I see that with fragments, it is easier to share data and plus you have better use of onpause to determine if the app went to background or fragment is being switched.
Am I missing something?
Thanks
(apologies for the long answer in advance)
I don't think anything is stopping you from doing that.
Having said that, How I look at activities is as a place where I can define how the entire UI screen for the current transition should look: which fragments it should include and how these fragments should sit side-by-side and more importantly how the application flow works.
Fragments within my activity should together make a meaningful screen with functionalities I expect and should be re-usable but they shouldn't know of other fragments presence. That's the job of the activity. In fact, I strongly abide by the rule that a fragment should never know of another fragment's existence (although nowadays you can include fragments inside fragments which kind of defeats this point). If I need to transition to a completely different set of use-cases, I prefer to use activities to handle the transition and the new layout and sets of fragments to use.
Do I have to do it? No. I can do it all in one main activity and do the transitions between these "quasi-activity fragments" myself but why would I want to do that when there's already a framework in place that does it for me? Using intents to initialize activities (to transition) is a lot simpler and cleaner to achieve than manually writing my own engine that keeps track of the state of all my fragments and decides which ones to initiate and which ones to get rid of.
Similarly, handling different orientations and device sizes is easier to do using built-in functionalities in activities than doing it yourself but again, nothing is stopping you from doing so.
Much easier to explain this in an example:
Imaging this use-case: I need to write an app that shows a list of songs and movies. When I click on one of the songs, it should open a media player and play it in a separate screen and when I click on a movie, it should open a video player and play the video. There are clear transitions here: From the main list to an audio player or a video player and back.
Doing this using only one activity and 3 fragments, I would have to replace the list fragment with an appropriate media player fragment (video/audio) and get rid of the list fragment myself (to preserve memory) when the user clicks on a list item. This is all fine and easy to do but what happens if I have to also add a way to add comments to songs/movies? Now I have to modify my main (and only) activity to understand the behavior that if someone is playing a song and clicks on the comment button, I need to transition again to yet another fragment and allow that fragment to capture/show comments.
As you can probably imagine, every time I add a new functionality, I have to modify my main activity to handle the transition since fragments are not meant to know about each other and are meant to be independent of each other.
What I would end up doing, if I only had one activity, would be to create a God class (my main activity) where the entire flow of my application is defined. Maintaining this flow will become more and more complicated as the app becomes complicated. Again, this is going on the principle of having independent fragments. If you don't care about your fragments knowing about each other, that's entirely different but then, in my opinion, you're doing it wrong :)
How would I do it using activities? I would still have 3 fragments but also would have 3 activities whose only job is to maintain the transitions to/from other activities and defining which fragment should be used. Transitioning between list activity to song activity is a simple intent and the freeing up memory is done for me. Now if the song activity needs to transition to a comment activity, it's simply another intent to a comment activity from the song activity. I don't have to change the list activity at all and in fact, the list activity will never know about the existence of this comment activity.
I know it's a very simplified example but as your app gets more and more complex and as you add more and more use-cases, you'll find that having multiple activities makes sense. You don't want to maintain the transitions between fragments yourself, otherwise you'll end up with a very complex framework which would slowly become unmaintainable.
Same logic would apply to having different fragments/layout depending on the orientation and the size of your screen. Again, by all means, you can handle these yourself in your only activity but the question becomes: why?
I think your question can be answered by two other questions:
What can Fragments do that Activities can't?
You can reuse fragments in layouts for phones and tablets, where the content that is presented in multiple screens on the phone appears as multiple columns in tablets.
Fragments can better retain instance state across configuration changes, with setRetainInstanceState(true).
You can nest Fragments inside other Fragments, each of which can have a different layout.
You can create Fragments without a user interface, unlike Activities, which should always have a content view.
What can Activities do that Fragment's can't?
Launcher Fragments don't exist, only launcher Activities.
Activities can be started from other apps with Intents.
Activities can be started as new tasks.
You can use Activities in older versions of Android, which is no longer that big of a deal since the usage rates of these older versions of android are pretty low nowadays.
While this list is certainly not comprehensive, there are many cases in which you could use either an Activity or a Fragment for the same content. Pick whichever one helps you keep your code organized. Fragments are good for reusable components where Activities are good for standalone capabilities. Personally, I tend to prefer using Activities unless there is a reason to use Fragments. I find that managing too many Fragments within a single Activity is tedious and error prone.
I've been developing for Android for a couple of years now, and I still find myself going back and forth on this issue: when should I be using fragments on a backstack versus putting each fragment into its own activity?
In the Android Fragment documentation, they show this diagram:
I understand the tablet use case perfectly, but for the Handset use case, I don't get why you would put each fragment into its own activity. I typically create one activity and add the fragments to the backstack (via FragmentManager). Is either one of these approaches considered the 'right' way to do it? If both are okay, what is a good rule of thumb to use for picking which approach to use?
This question is closely related, but I'm not totally satisfied with it. If you're supposed to use separate activities, what's the point of having a fragment backstack in the first place?
I doubt there is a right way to do it. There are likely some ways that are better than others in some circumstances, but for the most part, the answer will be "it depends."
I have noticed in the latest version (22.x) of the SDK with Eclipse that every Activity that is generated is nothing more than a placeholder for a Fragment. The Fragment is auto generated and contains the view logic. It seems like they want to make Activities nothing more than a placeholder/controller for Fragments. I don't think I agree with that. While I definitely see the use case for Tablets, I feel like this pattern should be used more on an as needed basis than as a general rule. This is just my opinion, but I think moving ALL of the logic into the Fragment sacrifices some of the benefits you get from using an Activity, so it is only a useful pattern if you need to re-use that fragment specifically.
If you're supposed to use separate activities, what's the point of having a fragment backstack in the first place?
Good question. I personally prefer to use many Activities and only use Fragments where I need to re-use the logic/views in multiple places. I think the flow of using startActivity and startActivityForResult and allowing the system to manage your activity stack is just a little easier than trying to manage a huge Fragment back stack and one Activity (again, just my opinion).
So when would I ever use the Fragment back stack? There was actually a very good situation for me to use it recently. I had an Activity that needed to build a very complex object. The Object needed many fields input to the user, so I created a Workflow that walked the user through this process one step at a time. I created a single Activity to handle the creation of this logic. Each step of the UI was a Fragment that took input from the user, reported back to the Activity, then the Activity loaded the next Fragment. The Fragments were added to the back stack so the user could go back to previous steps in the workflow.
Object1CreationActivity
FragmentA --> FragmentB --> FragmentC --> FragmentD
Communication between the Fragments and the Activity should be done with interfaces. This is important if we want to re-use these anywhere else. Because of this, I could re-use much of this code to create another Object.
Object2CreationActivity
FragmentB --> FragmentD --> FragmentE
To summarize, Fragments, Activities, the back stack, these are all powerful tools you can use to make Android applications. There may not be a great rule of thumb for when and how to use them, but as long as you are well versed in how they work together, you can use them as appropriate for your application.
fragments are light weight alternatives to activities....that is one way to look at it. e.g. i have my our app which has about 10-13 screens. Either
I create a new activity for each one of them. OR
I create only a few activities that are logically distinct in functional aspects ad swap view screens in them OR
I create 1 activity and delegate actual screen functional to fragments.
I find the third way much better and manageable. Its kinda saying that fragments allow reuse of view using the framelayout options. Further more you can devise an easy way to share data between fragments as against the heavy weight way of using a Parceable to share stuff between activities.
Also Android API folks are going to focus more on fragment based designs instead of activities so its better to stick with standards. Using fragments i a just a tad more complicated than using activities but is well worth the effort to learn them. Helps create scalable and quiet reusable screen views IMHO.
I know that Activities are designed to represent a single screen of my application, while Fragments are designed to be reusable UI layouts with logic embedded inside of them.
Until not long ago, I developed an application as it said that they should be developed.
I created an Activity to represent a screen of my application and used Fragments for ViewPager or Google Maps. I rarely created a ListFragment or other UI that can be reused several times.
Recently I stumbled on a project that contains only 2 Activities one is a SettingsActivity and other one is the MainActivity. The layout of the MainActivity is populated with many hidden full screen UI fragments and only one is shown. In the Activity logic there are many FragmentTransitions between the different screens of the application.
What I like about this approach is that because the application uses an ActionBar, it stays intact and does not move with the screen switching animation, which is what happens with Activity switching. This give a more fluent feel to those screen transitions.
So I guess what I'm asking is to share your current development manner regarding this topic, I know it might look like an opinion based question at first look but I look at it as an Android design and architecture question... Not really an opinion based one.
UPDATE (01.05.2014): Following this presentation by Eric Burke from Square, (which I have to say is a great presentation with a lot of useful tools for android developers. And I am not related in any way to Square)
http://www.infoq.com/presentations/Android-Design/
From my personal experience over the past few months, I found that the best way to construct my applications is to create groups of fragments that come to represent a flow in the application and present all those fragments in one Activity. So basically you will have the same number of Activities in your application as the number of flows.
That way the action bar stays intact on all the flow's screens, but is being recreated on changing a flow which makes a lot of sense. As Eric Burke states and as I have come to realize as well, the philosophy of using as few Activities as possible is not applicable for all situations because it creates a mess in what he calls the "God" activity.
Experts will tell you: "When I see the UI, I will know whether to use an Activity or a Fragment". In the beginning this will not have any sense, but in time, you will actually be able to tell if you need Fragment or not.
There is a good practice I found very helpful for me. It occurred to me while I was trying to explain something to my daughter.
Namely, imagine a box which represents a screen. Can you load another screen in this box? If you use a new box, will you have to copy multiple items from the 1st box? If the answer is Yes, then you should use Fragments, because the root Activity can hold all duplicated elements to save you time in creating them, and you can simply replace parts of the box.
But don't forget that you always need a box container (Activity) or your parts will be dispersed. So one box with parts inside.
Take care not to misuse the box. Android UX experts advise (you can find them on YouTube) when we should explicitly load another Activity, instead to use a Fragment (like when we deal with the Navigation Drawer which has categories). Once you feel comfortable with Fragments, you can watch all their videos. Even more they are mandatory material.
Can you right now look at your UI and figure out if you need an Activity or a Fragment? Did you get a new perspective? I think you did.
My philosophy is this:
Create an activity only if it's absolutely absolutely required. With the back stack made available for committing bunch of fragment transactions, I try to create as few activities in my app as possible. Also, communicating between various fragments is much easier than sending data back and forth between activities.
Activity transitions are expensive, right? At least I believe so - since the old activity has to be destroyed/paused/stopped, pushed onto the stack, and then the new activity has to be created/started/resumed.
It's just my philosophy since fragments were introduced.
Well, according to Google's lectures (maybe here, I don't remember) , you should consider using Fragments whenever it's possible, as it makes your code easier to maintain and control.
However, I think that on some cases it can get too complex, as the activity that hosts the fragments need to navigate/communicate between them.
I think you should decide by yourself what's best for you. It's usually not that hard to convert an activity to a fragment and vice versa.
I've created a post about this dillema here, if you wish to read some further.
Since Jetpack, Single-Activity app is the preferred architecture. Usefull especially with the Navigation Architecture Component.
source
Why I prefer Fragment over Activity in ALL CASES.
Activity is expensive. In Fragment, views and property states are separated - whenever a fragment is in backstack, its views will be destroyed. So you can stack much more Fragments than Activity.
Backstack manipulation. With FragmentManager, it's easy to clear all the Fragments, insert more than on Fragments and etcs. But for Activity, it will be a nightmare to manipulate those stuff.
A much predictable lifecycle. As long as the host Activity is not recycled. the Fragments in the backstack will not be recycled. So it's possible to use FragmentManager::getFragments() to find specific Fragment (not encouraged).
In my opinion it's not really relevant. The key factor to consider is
how often are you gonna reuse parts of the UI (menus for example),
is the app also for tablets?
The main use of fragments is to build multipane activities, which makes it perfect for Tablet/Phone responsive apps.
Don't forget that an activity is application's block/component which can be shared and started through Intent! So each activity in your application should solve only one kind of task. If you have only one task in your application then I think you need only one activity and many fragments if needed. Of course you can reuse fragments in future activities which solve another tasks. This approach will be clear and logical separation of tasks. And you no need to maintain one activity with different intent filter parameters for different sets of fragments. You define tasks at the design stage of the development process based on requirements.
There's more to this than you realize, you have to remember than an activity that is launched does not implicitly destroy the calling activity. Sure, you can set it up such that your user clicks a button to go to a page, you start that page's activity and destroy the current one. This causes a lot of overhead. The best guide I can give you is:
** Start a new activity only if it makes sense to have the main activity and this one open at the same time (think of multiple windows).
A great example of when it makes sense to have multiple activities is Google Drive. The main activity provides a file explorer. When a file is opened, a new activity is launched to view that file. You can press the recent apps button which will allow you to go back to the browser without closing the opened document, then perhaps even open another document in parallel to the first.
Thing I did: Using less fragment when possible. Unfortunately, it's possible in almost case. So, I end up with a lot of fragments and a little of activities.
Some drawbacks I've realized:
ActionBar & Menu: When 2 fragment has different title, menu, that
will hard to handle. Ex: when adding new fragment, you can change action bar title, but when pop it from backstack there is no way to restore the old title. You may need an Toolbar in every fragment for this case, but let believe me, that will spend you more time.
When we need startForResult, activity has but fragment hasn't.
Don't have transition animation by default
My solution for this is using an Activity to wrap a fragment inside. So we have separate action bar, menu, startActivityForResult, animation,...
The one big advantage of a fragment over activity is that , the code which is used for fragment can be used for different activities. So, it provides re-usability of code in application development.
use one activity per application to provide base for fragment
use fragment for screen ,
fragments are lite weight as compared to activites
fragments are reusable
fragments are better suited for app which support both phone & tablet
You are free to use one of those.
Basically, you have to evaluate which is the best one to your app. Think about how you will manage the business flow and how to store/manage data preferences.
Think about, how Fragments store garbage data. When you implement the fragment, you have a activity root to fill with fragment(s). So, if your trying to implement a lot of activities with too much fragments, you have to consider performance on your app, coz you're manipulating (coarsely speaks) two context lifecycle, remember the complexity.
Remember: should I use fragments? Why shouldn't I?
regards.
I use Fragments for better user experience. For example if you have a Button and you want to run let's say a webservice when you click it, I attach a Fragment to the parent Activity.
if (id == R.id.forecast) {
ForecastFragment forecastFragment = new ForecastFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_content, forecastFragment);
ft.addToBackStack("backstack");
forecastFragment.setArguments(b);
ft.commit();
}
In that way the user won't have to move in another activity.
And secondly I prefer Fragments because you can handle them easily during rotation.
It depends what you want to build really. For example the navigation drawer uses fragments. Tabs use fragments as well. Another good implementation,is where you have a listview. When you rotate the phone and click a row the activity is shown in the remaining half of the screen. Personally,I use fragments and fragment dialogs,as it is more professional. Plus they are handled easier in rotation.
Almost always use fragments. If you know that the app you are building will remain very small, the extra effort of using fragments may not be worth it, so they can be left out. For larger apps, the complexity introduced is offset by the flexibility fragments provide, making it easier to justify having them in the project.
Some people are very opposed to the additional complexity involved with fragments and their lifecycles, so they never use them in their projects. An issue with this approach is that there are several APIs in Android that rely on fragments, such as ViewPager and the Jetpack Navigation library. If you need to use these options in your app, then you must use fragments to get their benefits.
Excerpt From: Kristin Marsicano. “Android Programming: The Big Nerd Ranch Guide, 4th Edition.” Apple Books.
Some wrong ideas:
Always put an activity in your app and handle different screens with fragments.
Write the UI code directly in the activity.
Handle navigating between screens (I don't mean tabs, I mean for example full-screen views) by fragments.
Activities can be replaced by fragments.
Here is the thing!
Fragments are designed to implement reusable parts of UI and use them in any part of the app that is needed. They are not designed for substituting activities.
When we must use each of them?
When we have an independent screen in which there are some different UI parts (tabs, expandable screens, partial screens, etc...) we should use an activity with some fragments to implement and handle different UI parts separately in the same screen.
Each independent part of the application is actually a component that is conceptually different from other parts and it needs to have an independent activity. For example, the login part may contain some different scenarios like using username-password or using fingerprint. Each scenario can be implemented by a fragment and all login-related fragments should be handled by LoginActivity. But for example, the part of the orders in the application doesn't have a conceptual relationship with login, so it must have a different activity and of course, it may contain some fragments like OrdersFragment, SubmitNewOrderFragment, and etc that all of them must be managed by OrdersActivity.
Do not implement a UI directly in an activity. Always implement UI in fragments and add those fragments in the activity even if there is only one fragment in that activity. It helps you to have more reusable code and change UIs easier.
Never use fragments to navigate infinitely in the application even if you force the user to have a limited number of fragments in the back stack. The fact is that when you add a new fragment into the back stack and remove it, it will not be removed from the memory unless the parent activity gets destroyed and it is only not visible. So when you are using fragment manager back stack, by navigating multiple times between fragments in the same activity (especially in the case of you create a new fragment on each navigation and put them into the back stack) you will get an OutOfMemoryException in the application.
I hope it to be helpful.
This question needs to be reevaluated since Jetpack Compose has reached stable.
Jetpack Compose is Android’s recommended modern toolkit for building
native UI.
from https://developer.android.com/jetpack/compose
The typical jetpack-compose architecture is:
Single Activity, multiple composables, and glued together by jetpack navigation.
Note there's no (need for) Fragments anymore.
See Now in Android for a sample.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
First question on Stack Overflow, apologies if it is not well formed.
I am developing a relatively complex tabbed app, and already had the basics set up before coming across information that ActivityGroup and TabActivity are deprecated, and the preferred model is to use views.
I have had no trouble using views, this is a question about architecture rather than syntax (which is why I haven't posted any code). Specifically, how should I go about restructuring the app to use views instead of Intent launched Activities.
The app has five tabs; two hold a single layout, no problem there. The other three tabs are running an ActivityGroup with 2-5 different Activities (i.e. a tab running an activity for settings, where clicking each view starts a new Activity dealing that particular setting, pressing the back button returns you to the broader settings activity/view). If I were to keep each Tab as a TabActivity, it would still be fairly easy to change those internal transitions to views as opposed to separate Activities.
The main question is using ONLY views, no TabActivity/Activity group at all. The vast majority of the research I've done has been discussion about whether to use Activities or Views, or about specific syntax. I haven't been able to gather a clear idea of how to actually MAKE the transition to views across the whole application.
If I were to do so, wouldn't the entire app now be running in a single Activity - the one hosting the tabbed layout?
If (1) is true, how to manage this? Despite ActivityGroup being deprecated, all of the Android documentation still seems to state that it is preferred to use separate Activities for separate aspects of functionality--which makes sense. Did the Android development team simply decide that the costs to the stack and the device made the TabActivity implementation ineffective?
If the application is running in a single Activity that manages different views for each tab (and then different views WITHIN a tab when necessary), should I have one single enormous onClick method to handle all clicks from any clickable view, handling input based on which view is active? Or should I register and de-register all of my Listeners programatically?
With a single Activity, won't any click listener or any broadcast receiver be running all of the time, consuming resources even when unnecessary?
With a single Activity, the back button would exit the entire app from any point in its functionality. If I am using views, won't I have to consistently override onBackPressed() and carefully manage the app behavior to force it to behave "like an Android app?"
AM I THINKING ABOUT THIS COMPLETELY WRONG? It's possible that I am unintentionally attempting to recreate ActivityGroup and TabActivity functionality using views instead, when I should be taking an entirely different design approach to using tabs and Views.
When the people at Google say we shouldn't use activities as tabs anymore, and Mr. Mark Murphy so emphatically agrees, I'm inclined to believe. I simply haven't been able to research-up a way to switch without resorting to recreating a lot of Activity functionality by hand (which would probably include a variety of dirty hacks).
Appreciation in advance for anyone willing to tackle such a vague and overwritten topic.
Using Fragments is the new standard for performing tabbed style ui components, I think you must have just overlooked them because they are the missing piece to all your above questions. Good luck.
Don't forget that using the compatibility library brings Fragment support all the way back to 1.6.
And here is an easy Google recommended tutorial on using Fragments within a TabHost.
About 3) Split your app in as many Activities as you have different parts of the app. Today I'd even go for Fragements that can be easier composed to different layouts when you e.g. make the app for Phone and Tablet.
Most of the time, you can just set up the onClick listeners in the respective xml layout definition files like this:
<ImageButton
android:id="#+id/new_tweet_back_button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="left"
android:onClick="done"
android:src="#drawable/back_button"
android:layout_below="#id/CharCount"
/>
Here the android:onClick attribute points to a method that implements the handler.
You don't need to de-register anything.
And instead of Tabs I'd go for the ViewPager which makes imo a much more natural experience with just swapping views by swiping left and right (see e.g. G+ app or market app)
As a final answer to my own question:
Using fragments in tabs DID solve all of the above issue.
So, instead of an Activity defining tabs containing other Activities, I have one large FragmentActivity that sets up and switches the views of the various fragments. The click methods defined in the XML for each tab view belong to the FragmentActivity, and I opted to have each onClick call a corresponding method in the appropriate fragment (passing a context if necessary) so the code for manipulating each view programatically can stay in the appropriate class.
THIS IS FOR A PHONE USING THE COMPATIBILITY PACKAGE, not a tablet or Honeycomb, so I can't speak for those unfortunately.
This solution seems to have worked well for me. I recommend anyone looking at the same issue to check out:
thepsuedocoder blog post:
http://thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/
Android documentation on Fragments:
http://developer.android.com/guide/topics/fundamentals/fragments.html
The API demo "Fragment Tabs"
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/index.html#Fragment