ActivityA launches fragmentA. I need to launch fragmentB. There are 2 ways of doing it, but I dont know which is the best way First way, create a ActivityB which would launch FragmentB. Therefore, ActivityA--> ActivityB--> FragmentB.
The second way, is just replacing FragmentA with FragmentB
Fragment b = AddRecordFragment.init(Integer.valueOf(f.getId()));
getFragmentManager().beginTransaction().replace(R.id.container,b).addToBackStack(null).commit();
When I took the Udacity course, they perferred the first way, but I cant see the logic in creating an second activity (activityB) for the mere purpose of launching an Fragment. Can you tell me what is the advantages and disadvantages to each ?
There really is no "right" way to do these kinds of things. There are recommended ways, there are best practices, there are common usages -- but all of this depends on what you, the developer, need to do to provide the best experience for your users and the best clarity and organization for fellow developers. Thinking through these things will give you the best answer for your particular scenario.
To address your particular question, think about what an Activity does, what its purpose is, and then think through why you would need Fragments. From the Android docs:
An Activity is an application component that provides a screen with
which users can interact in order to do something...
For Fragments:
A Fragment represents a behavior or a portion of user interface in an
Activity.
So already, even from the first sentence of each doc, we see a defined purpose for both components. An Activity is, well, an activity for the user. It's a screen with a purpose of allowing the user to DO SOMETHING. A Fragment, on the other hand, is a modular design that provides UI and other elements of interaction and data for the user that gets attached to an Activity. In other words, it helps the user do the thing that the Activity wants them to do, by either providing some point of interaction, or some visible form of data.
So now that we've clarified the purpose of these two components, ask yourself what the purpose of Activity B would be in your question. Will it provide the user with something new to do or see (even if through the use of Fragment B)? Will it provide something different from what the user was doing in Activity A? If so, then yes a new Activity is probably the best design choice. But if Fragment B is just another way of doing whatever it is the user is supposed to be doing in Activity A, or some sort of extension of that activity, then your best choice would be for Activity A to simply replace Fragment A with Fragment B itself through a FragmentTransaction.
The entire idea of working with fragments is to create a flexible design. Meaning you can use same view container to display different content with different functionality. So, it's clear that if you need to display a different fragment, you should replace it in the container.
In some cases you may prefer using a different activity, f.e. while launching settings, but if it's just a different content that can be contextualised with the same activity, definitely use fragment manager to replace in container.
It is not about the advantage, it is about what you want to do.
A Fragment represents a behavior or a portion of user interface in an
Activity
Now it if you want the Fragment to be a portion of the first activity you launch it the second way. That is
Fragment b = AddRecordFragment.init(Integer.valueOf(f.getId()));
getFragmentManager().beginTransaction().replace(R.id.container,b).addToBackStack(null).commit();
But if you want it to be a portion of the second activity you launch it the first way.
Depends on which activity the fragment should be a part of.
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.
I am currently writing an Android app for my Masters final project. The app has two Activities and both have layouts corresponding to each activity. I also have a settings activity with settings fragment but I am not concerned about this one.
Activity A currently has a Spinner and a button which when pressed will do some stuff and then launch a Activity B. Activity B displays a chart, contains a couple of actions and a button to go back to Activity A.
Neither of these activities have Fragments currently but I am curious if it would be better to include Fragments. As far as I can tell using a Fragment wouldn't hinder performance so at this point it would be a cosmetic change.
Fragments are usually needed if you need to re-use some specific layout.
E.g--> If you have an app which displays movies, you can click and get movie details.
Here it would be better to use fragments as the layout would be the same for each movie and only the content would change inside.
In your case however, since there is not need for such frequent scenarios, you really do not need fragments.
If you want to change the content without changing your activity due to some actions of user, implementing UIs inside Fragments can be useful. Just set the the desired fragment inside Activity by using its FragmentManager. However, otherwise don't think about such change (shifting lots of code/layout from activities to fragments) in the code.
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.
referring at the diagram below:
http://developer.android.com/guide/components/fragments.html
Could someone please please explain why Google suggests to use 2 separate activities on a Phone and a single activity on a Tablet?
If I have code in activity A to manage Fragment B (for a Tablet) why should I repeat the same code in Activity B for a phone?
It seems that for a Phone I can still use 1 activity as well (only activity A) and replace fragments, this could reduce redundant code?
Thanks.
The reason is, essentially, that phones are small. Really small. Tiny, in fact.
Take the classic scenario of an email application. The two fragments in that scenario would be the Message List (Fragment A) and Message Content (Fragment B). On a tablet, where you've got space, you can combine them into a single activity, concurrently on screen, comfortably. On a phone, however, you need to carefully manage your screen real estate, so you should split them into the choose-a-message phase (Activity A showing Fragment A) and the read-a-message phase (Activity B showing Fragment B).
By developing them as fragments, similar to user controls in other platforms, you can use the same fragments in the same codebase on a tablet and a phone, composing the activity from existing fragments.
I get what you mean..
You could use a fragment container and replace the fragments, define interface for selection callback. Google just does it this way maybe its clearer for those who come from the activities world i guess.
Rejinderi's solution should work. I think that either that implementation or the one from Google's example can be a reasonable choice. It depends on what you are trying to achieve.
Personally, I prefer Google's example for the following reasons:
Separate activities means you use the activity back stack. In some (most?) cases, the fragment back stack is fine, but the default transition is different. You may prefer one over the other for UX reasons.
If you want to capture an intent, it may be unclear why ActivityA is capturing JobB.
In my experience, the logic for handling FragmentB without FragmentA is (a bit) different, and breaking it into it's own activity helps separate that logic, and makes everything more readable.
Menu options may also change. Again I find the separation of logic more clear.