Is it a good idea to build an application fully in fragments? - android

I'm starting to build my new application and I'm trying to go the right way from the start to make my life easier later in maintaining and extending the application.
I saw applications that are probably built in fragments only. Of course, there is a host activity that hosts the fragments, but everything else is in fragments.
I suppose they have a Main activity that has the action bar and a layout to host the content in it. Everything else, including different screens such as Login, Home, Settings, Profile, ... is in fragments.
When we click on an item in the navigation drawer, for example on the Settings button, they simply change the content fragment, instead of launching a new activity for Settings.
Is that a good idea to build the main screens all in fragments, and just have one activity to display them?

Yes, it's a good idea to split up your UI into Fragments.
Some advantages:
-reuse in multiple Activities
-self-contained, modular UI
-rearrange fragments
Cons:
-it's a bit more work
-slightly higher learning curve

Related

Best practise to use bottom navigation in android: activity vs fragment

I am coming from iOS and working to port an iOS app on android. In iOS there is the storyboard where you can connect different view (activities) and embed them into tab bars and navigation bars. I am having an issue to understand what is the best way to implement bottom navigation in android...
Let say I have 3 bottom navigation items with the following
tab1
page1.1
page1.2
tab2
page2.1
page2.2
page2.3
tab3
page3.1
page3.2
page3.3
As an example in tab1 I have page1.1. Then let say I have a button in page1.1 which bring me in page1.2. If I go back from page1.2 I want to go back to page1.1. Same story for page2.1, I can go to page 2.2 and from page2.2 I can go to page2.3. I also want to go from page3.2 to page 1.2
I have read fragments are the best way to do it (each page.x is to become a different fragment with a different layout) but it does not seem very easy. I have also read I can use activities but many suggest not to use it
What do you recommend that I focus on? Are there any other solution to consider on top of fragment and activities? Thanks
You should use Fragments with a Single Activity. If you don't, you will have to copy/include one bottom bar in multiple Activities. It might be useful in some cases however when Activity is switched, your bar will redraw which might turn out to be a bad user experience.
I have read fragments are the best way to do it (each page.x is to become a different fragment with a different layout) but it does not seem very easy
Using Fragments might actually make it easier than if you use Activities. If you use Fragments, you can have one Activity be in control of every fragment that is being displayed, meaning that you can control navigation based on which fragment is being shown. This way, you can handle some special scenarios that do not fall into usual navigation behavior.
Doing the same in Activities would be a little more difficult since you'd have to continuously pass around data in Intents and it would be difficult to control the behavior since your logic will be spread across Activities.
What do you recommend that I focus on? Are there any other solution to consider on top of fragment and activities?
These two are only recommended solutions. If some of your UI elements are same in all pages while some part of it is changed constantly, then its best to use Fragments with single Activity. For screens that are completely different or that are not part of your navigation flow, you add more Activities for them instead of Fragments.
For example, You can use Fragments in One Activity with Bottom Navigation Bar, but for settings screen or profile screen, you should make separate Activites.

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.

It would be correct to use the NavigationDrawer to open Activities, not fragments?

My application basically has one main activity. Within it there are three tabs, each with a fragment. Something similar to the layout of whatsapp.
To add more functionality to the application, I saw that the NavigationDrawer would be a good option. But because of my application running with a main activity with children fragments, I wonder if it would be a bad practice loading activities and not fragments, when the User clicking on any item NavigationDrawer.
Or does the best meneira would turn my MainActivity in a fragment? It would give me a great job ..
I would like to suggestions =)
You can use the NavigationDrawer to open new activities. Basically just make each of the Activities have the same-looking Drawer and the user experience will be same as if you were replacing Fragments.
However, I would discourage this. I have been working with apps that mixed Fragments and Activities for the NavigationDrawer and the outcome was problematic, especially when it came to backtracking and saving state. It did work, but required hackfixing and some illogical code.
The best practice for the NavigationDrawer is to have one "container" activity which does little more that just exchanging Fragments in a FrameLayout it holds. The rest of the logic would be in the Fragments. This way the app is easily extendable and the backstack is handled by the platform.
I prefer Fragments but there is no problem to open new Activities. Instagram does something similar. It has tabs (I know that you want to use NavigationDrawer, but this is just a example), and one on these tabs open a new Activity, with the X button to close the Activity.
Instagram Main Activity:
New Activity with close button:
The Series Guide Android application does exactly the same. It opens Activities from the Navigation Drawer. Such Activities extend the BaseNavDrawerActivity. The Activity's start and exit animations are custom to make the transition looking smoother.
I would recommend this approach since it's much more easier to manage Activities' back stack than Fragments'.
Proceed happily with opening activity as well. Make sure you put the back button on the opened activity so that user would have clear idea that which screen is the primary.
But wait..
If you are worried about whether you are following the standards (industry) or not then read below:
If all your activity has the equal importance for users (including the tabbed one) then recommended way is to use the fragments and on the other side if you don't want people to get distracted by navigation drawer icon or tabs then better to open a new activity with just a back button on top..
I hope it would give you idea how to proceed..

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.

Patterns when to use Activity Transition vs Dynamic Fragments

Are there any patterns on how to handle UI Transitions in Android Activities vs Fragments? I am currently looking into a UI that has at most 3 columns in Landscape.
I would like the UI to start with 1 column all the way across the screen and then on selection of something move in the second column and then on clicking on something in the second fade in the 3rd on tablets and phones and fade out the 1st column on phones.
I am wondering when I should do this as an Activity transition and when I should just use Fragments with Views that Appear. As far as I have read fragments can be moved over to other activities so my choice is either implement Activities with static column layouts that then transition taking the fragments with them or have one Activity with all 3 columns and have the Activity manage the Appearing of the Fragments. Both approaches could work but I was interested in pros and cons from as many angles for both solutions.
There are two questions similar to what I am asking but don't quite answer mine
Two panel UI with Fragments vs Separate activities
Android Honeycomb: layout problem - hide/show FrameLayouts
Fragments can seem like more code up front (since you're putting a view in a fragment, and a fragment in an Activity, instead of just a view in an Activity), but they're great at saving you from headaches in just this kind of situation- Definitely go with Fragments. They even handle the transitions for you.
We have some sample code called "Honeycomb Gallery" you can take a look at here, which has a two-column-plus-actionbar layout, and the ability to show/hide the leftmost column. This should give you a good head start in figuring out how to do layout for multiple fragments and show/hide them.
FYI, one important trade-off to using multiple fragments in an Activity instead of multiple Activities, is that fragments don't directly respond to intents - For instance, if you had a note-taking app where "View Note" page was an Activity, and you changed it so that there was a "view note" Fragment inside the main Activity, then you'd have to set it up such that the main Activity received a note ID AND a note action (create, view, edit, whatever) in the Intent, as opposed to just having the "view note" activity receive the note ID in the Intent. The main Activity would then need to set up the fragments on the page accordingly. Not a huge deal, but if external accessibility to various parts of your application via Intent is important, then it might be easier to break your app out into a few Activities, as well as use fragments to represent the individual components.
Based on the page The Android 3.0 Fragments API, an Activity is stand alone while a fragment can be though of as as a mini-Activity, which must be hosted within an actual Activity.
It goes on to say that the introduction of the Fragment API gave the android developers the opportunity to address many of the pain points developers hit with Activities, so in Android 3.0 the utility of Fragment extends far beyond just adjusting for different screens:
I think that using a single activity for an app is not necessarily a wrong decision, just a matter of style. It is a decision that you should make based on what you are trying to accomplish.
However, the introduction of Fragments was seen to solve real world problems. Based on that alone, I would recommend that you writing some "Proof of Concept" code and evaluate the results. At this time, this may be the only real world test that will matter
Use Activities for Full Screen
Use Fragments for Part of or no Screen (but not a service)
In my main application, there is on-screen tabs in a horizontal scroll-view I wanted to persist across multiple sections of the app. Sections include
News,Photos,Videos,Schedule etc. All single-user focusable tasks.
The main Application that houses it all is a application, and the tabs are just a view which call the fragment Manager.
However, I use Activities for complicated user activities deeper in the application. E.g. if someone plays a video, views a item detail page and the photo-gallery/slideshow sections, because they are all full screen components.
There is no need to show/hide fragments when transitioning to full screen because the activity stack handles everything you want to do it quickly and easily, and keep your code minimal and clean.
So I have Activity -> houses fragments -> launch full screen Activities for special commands.

Categories

Resources