To fragment or not to fragment? - android

As I've started to adopt Fragments more and better but also as Fragments functionality is increased (Fragments in Fragments, MapFragments) I'm starting to reach a point where I need to define when I should make a new View/Action as a Fragment or as an Activity?
An Activity is defined as:
An activity is a single, focused thing that the user can do.
But a Fragments have kinda taken that definition instead as described in the docs:
For example, a news application can use one fragment to show a list of
articles on the left and another fragment to display an article on the
right—both fragments appear in one activity
This is two things the user can do in one Activity with two Fragments.
So I'd like some input/help to figure out what is the best approach to decide if I should make a new action/view as a Fragment or as an Activity?

The answer depends on you and your development practices (or those of your company). However, my opinion is this: At a minimum, if you think the functionality being developed could be used within multiple Activities, or if it could ever be used in an Activity alongside another view (as on a tablet), then you should make it a Fragment.
We've recently adopted the philosophy of creating Fragments in all cases. Our Activities are now just top level coordinators, basically the glue that brings things together. This makes for a consistent and flexible architecture. This is important to us as we have numerous engineers at a couple of locations working on code.

An Activity is defined as: "An activity is a single, focused thing that the user can do"
That is more an issue of dated documentation than anything else. Activity has that same definition... when we are on a smaller screen size (e.g., phone). As you move up to larger screens, the odds of an activity being more complex than "a single, focused thing" increases.
So I'd like some input/help to figure out what is the best approach to decide if I should make a new action/view as a Fragment or as an Activity?
Here is my general heuristic:
If you anticipate that such-and-so piece of UI might exist standalone on a phone-sized screen, but be used in tandem with something else on a tablet-sized screen, make it a fragment.
If you anticipate that such-and-so piece of UI will always exist standalone, just create a simple activity.
If you anticipate that your ability to anticipate is not that good, err on the side of making more fragments. For example, you might say, "well, help will never need to be alongside anything else" and make it be an activity. Then, if you realize that other pieces of UI might benefit from the help being side-by-side with them rather than off on its own -- so the user can read the docs and perform the actions at the same time -- you will regret not having made help be a fragment, as you will have to do some re-work.
If such-and-so piece of UI would never exist standalone -- in other words, if it is more like a single widget than a full activity -- and you anticipate using it on multiple projects, make it be a single widget, in the form of a custom View or ViewGroup.
But, as jsmith indicates, there is no universal right or wrong answer. BTW, AFAIAC, jsmith's answer is the correct one here, but I was going to be way too wordy for a comment on his answer... :-)

I've been developing in Android since 1.5 so I have been developing from quite some time Activities and recently Fragments.
Quite frequently fragments left me with a sour taste in my mouth... an example was when I needed a kind of paginated Dashboard with buttons. For that I used a ViewPager + 1 fragment per button. I had all kind of problems because before Android 4.2 fragments couldn't be nested.
Another problem was the asynchronous mode of function of the fragments that when the needed to be moved from one place to the other quite rapidly it had all kind of misbehaviours.
Don't think that all was bad... in more simple cases, the use of fragments worked quite nicely.
So, in my opinion, whenever you have an area that is self-contained, that isn't moved frequently on the views, that can be reused in several screens and also you support tablets (or my in the future), use it.
If you need nested fragments, views that are re-arranged quite frequently, or code that will not be reused, don't.

Related

When we should use fragment and when we should use activity? [duplicate]

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.

Should I replace Android Activities by Fragments?

I have a large Android game in which there is an Activity for each logical screen.
(Splash screen, start screen, level chooser, game screen and Settings are distinct Activities).
Everything is working fine right now.
If I rewrite everything so that there is only one activity and the logical screens are Fragments, Will it reduce RAM or CPU consumption?
After years (two+) of saying "Fragments are the way to go", I would never replace activities with Fragments again.
Using fragments to rehuse certain components is fine. Using fragments for dialogs is also fine, but I have now realized how awful the Fragment implementation is, how awful the Fragment lifecycle is and how unpredictable (and buggy) FragmentManager tends to be under certain circumstances. Go ahead an spend some time googling around and you will find all the "edge but not so edge" cases where hacks have to be implemented to work around a "by design" buggy behavior.
Sometimes you have to extend or copy the source code of these classes from the Android Source Code to modify a private or protected field…
Don't get me wrong, Fragments work. But they are not the solution to all your problems (they are possibly the source of new ones in the mid-long term). If you already have Activities, enjoy that! In fact, the new Transition Frameworks with Shared Elements is a clear indication that Google wants you to use more activities ;)
This is my personal opinion after working in roughly six mid-large sized Android projects (some are popular and you've probably used them!) ;)
As far as I know, no, Fragments have (near to) no impact on RAM or CPU.
An Activity contains certain elements and performs some functionality. A Fragment is loaded onto an sort of base Activity, like an Activity with no more than an ActionBar. The rest is filled by the Fragment.
Also check out:
android - need some clarifications of fragments vs activities and views
Activity or Fragment which is better way to use for performance and reliable?
No, it will probably increase it (as you will have more classes) but only marginally.
The benefit of using fragments is to have reusable "blocks" that you can move around depending on your needs. For example for a specific activity you could have a layout where you have your main window on screen and clicking on an item creates an new activity with some details. With fragments, you could create a layout for tablets where the main window takes only half the screen and the rest is used for the details fragment, witout having to rewrite everything.
The main benefit of fragments to me is easy data sharing. Between two activities, data has to be passed in relatively primitive types...string, int, arrayList, etc.
However between fragment and activity, data can passed back and forth in complex classes.

Should each Fragment have its own Activity?

Android Studio 0.8.10
I have developed an App that has 3 fragments. I have just used 1 Activity and when I want to display a different fragment I just replace the existing fragment with the one I want to display. However, as I have 3 fragments now, and maybe more in the future, I think this will get harder to manage.
I am just wondering what is the design pattern when programming with multiple fragments, should each fragment have its own activity?
I will be scaling this to Tablets in the future, so I am not sure what impact this will have if I stick with the multiple fragments and single activity.
Many thanks for any suggestions,
should each fragment have its own activity?
Yes, but you can also use nested fragments.
I think this will get harder to manage.
you are right but
i think you must match your app with some other widget for example if you have multiple fragments that want to show one after the other use viewpager or you can use horizontalscrollview. you can create tabs and sync them by viewpager and so on.
Yeah, this can be really hard to figure out. I think a pretty good analogy, from the web application world, might be a servlet and a frame.
An Activity is like a servlet. It is one page in your app's workflow.
A Fragment, on the other hand, is like a block of content. It might appear in several different contexts and it might be served by several different servlets.
In MVC terms, the activity is largely part of the controller. A fragment, on the other hand, is more like a view include.
Much of the time, those two concepts align. A page in the workflow frequently contains exactly a single block of content. As you have, wisely, noticed, though, when you get more screen real estate (on a tablet), it is entirely possible that a single activity will display more than one fragment.
A single activity, on a tablet, might show, for instance, both a list of selectable items, and the details for the currently selected item in that list. When you have less space on the screen, though, those two things would be displayed as separate workflow items. Clicking on an item in the list invokes an entirely new activity.
The content is constant. The workflow changes.
Most modern applications will use a Fragment to display Activity content. It makes the application more flexible and easier to adapt to wildly different screens.

Dilemma: when to use Fragments vs Activities:

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.

Are Fragments and Fragment Activities inherently faster than Activities?

Are Fragments and Fragment Activities inherently faster than Activities?
If I don't need to load my activity in fragments, should I be using FragmentActivities and Fragments over Activities?
Reason I am asking is because I have been using Activities, exclusively, for years, and the Facebook SDK as well as Google Maps 2.0 have forced me to use Fragments, and I wonder now if they are inherently "better" or not, versus some other implementation.
If this "not constructive" or "too open ended" then obviously the answer is "no". But if there are some Google developer documents or blog on this exact subject, then I would like to be aware of it
I became a believer in Fragments in my last application. Whether or not they are computationally faster, they feel faster because you can swap them in and out basically instantaneously, including full support for the back stack if you do it right (call addToBackStack() on the transaction, or something very similar).
I now use Fragments / Fragment activity for all navigation I want to feel very quick, like clicking on a row to get more details. I only launch new activities for when I want to do a fundamentally different thing and have a clean slate to work with. For instance, I usually have a LoginActivity that deals exclusively with logins/registrations, and at least one more that is the core of the app.
But the fundamental benefit of Fragments still remains their flexibility. I can show fragments on top of other fragments, re-arrange them on different screen sizes, etc. But there are loads of other benefits. It just takes a while to feel natural (just like Activities did at first).
One caveat, I always regret embedding fragments in my layouts. I can't give exact reasons here off the top of my head, but essentially you just lose some flexibility. Instead, I build a normal layout for each fragment, and add a placeholder view in the activity layout, create the fragment programmatically, and use transaction.replace() to add it to the layout. Perhaps because this is the main way I swap fragments in and out of that placeholder view, and prefer to just have a single way of doing things where possible.
yeah, fragments are introduced exclusively for supporting large screens to use the area efficiently.handling fragments is very easy and in terms of memory.but nested fragments makes trouble
Fragments are very useful if you want to split a screen. So you can have different views within the same screen. Another way of using fragments, lets say you've got tabs to categorise items. Could have clothes, shoes as your tabs. Each tab will have a fragment to hold the products. The tabs could either held in activity or a fragment. I do find fragments a slightly faster than activities but really its not something you would really notice in most cases. Regardless if they was intended for speed or not they still seem/feel little quicker.
The downside of using fragments, is certain callbacks like onBackPressed is only in an activity. Fragments has no access to this. I often find its best to minimise how much activities as possible. Also don't forget Activities aren't just views, they're also a screen. Whereas fragment is only a view and doesn't have a screen. tool/action bars etc. are also only for Activities however if your using a custom toolbar, you can use this in a fragment by implementing onTouch(if not button but some object) or onClick(buttons) the method for these will give you what you need. So really there are some drawbacks but there is almost a workaround for at least some of them.
I do agree Fragment transition is awesome and pop the stack when working with back buttons and onBackPressed Does the trick.
I always use a switch in parent activity etc. to see, which fragment needs to be in view, i often update it using interface passing bundle etc. Not sure if anyone else has found a more efficient way or not. But I do find it really useful when switching views.
Yep fragments are top brass for most things.

Categories

Resources