This is the image explaining the usage of fragments. The first image shows two fragments and two activities.
Lame doubt. Why use two activities when the sole concept of using fragments is err.. using fragments instead of switching activities.
Depending on your goals you can do it either way.
The method shown in the guide can be implemented entirely in XML layout files so it is a better method to teach to a new user of fragments.
The method you suggest requires the developer to manage fragment transactions in code, which is not too difficult, but why do it if your app does not have any special behavior that requires the extra work.
Also, since the animated transitions between fragments look different than activity transitions, your method will reveal the use of fragments at the user level. The method in the guide uses fragments as a modular programming technique that is transparent to the user.
You end up with an app that uses available space on all device types, but on a small device it acts just like a classic app that users already understand.
The idea is that when you have extra room (such as on a tablet), you can display the content from what would have been two activities side-by-side rather than as two separate activities.
Think about a mail application. On a phone, you fn really only fit the list of mail on a screen, and you click on one to open the content of that mail on another screen.
If you did that on a tablet, there's a huge amount of wasted space; you can display the list of mail on the left side of the screen, and the selected mail's contents on the right side.
Because the list UI is the same in both examples, and the mail-display UI is the same in both as well, you can reuse that UI by including them as fragments. The logic for those UIs is also self-contained in the corresponding Fragment classes.
This allows the user to see more content with fewer activity switches.
Related
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.
I'm currently developing a little application that uses a login screen and a main screen. I'd been watching how another developers had been made the screen switch, some developers adds and remove fragments on run time, anothers have an Activity for each view (in my case that will be a MainActivity with the main_activity layout, and the LoginActivity with the login_activity layout). And I don't know wich is the way to go. I think that have a fragment for each view will be the solution with more sense, but I want to listen some opinions before continue.
There might be others who disagree with me, but in my opinion, Fragments are better suited when you want to keep a part of the screen static and change something in the other part (analogous to AJAX in websites).
Activities should be used for individual views in those cases where there is only one thing happening on the application front-end.
On the other hand if you have a Gmail like layout (with static links to Inbox, Sent, etc. on the left hand side and a dynamic list of mails on the right hand side of the screen), Fragments is the answer.
But since you have two different screens for layout and main, in my opinion, it would be neat if you used different Activities for the layouts and used Intents to navigate around.
For two completely different Activitys such as Login and Main I think you want to use two different Layouts and two separate Activitys and no need for fragments. However, you may want to use fragments inside any of them as #swayam suggested depending on what you want to do inside of them. You need to look at the docs and decide which is better suited for your needs. No one can really decide that for you.
Activity
Fragments
This question already has answers here:
Dilemma: when to use Fragments vs Activities:
(17 answers)
Closed 4 years ago.
I often need the different parts of my applications to have their own special behavior and UI, and I don't know how fragments can help. In most cases, I think it is quicker to create 2 different activities (e.g., 1 for tablets and 1 for handsets), and to share the common behaviors and events in a third class.
So, keeping this in mind, why should I use fragments ?
Fragments are more of a UI benefit in my opinion. It's convenient for the user sometimes to see two different views of two different classes on the same screen. If, in your moment of creativity, you decide it would be nice to display your application with, say, a listView that takes up half the screen and a webView that takes up the other half - so that when you click on a list item in fragment A it passes an intent to the webView in fragment B, and suddenly you see what you just clicked without the app switching activities - then you could use a fragment. That's just an example I came up with off the top of my head.
Bottom line: Fragments are two or more activities on the screen at the same time.
The benefits I see when using fragments are:
Encapsulation of logic.
Better handle of the lifecycle of the fragment.
Reusable in other activities.
The drawbacks I see are:
More code(For example, instantiating a fragment manager, adding the fragment transaction, writing the callbacks of the fragment)
Communication between fragments and activities is harder. As #jonney said it, you would need to deal with a parcelable interface to serialize your objects you wish to pass.
So, when deciding to use a fragment, I would ask myself the following questions:
Is the lifecycle of the fragment different from the activity's lifecycle?
If the lifecycle is different, you get better handling of the lifecycle using a fragment. For example, if you want to destroy the fragment, but not the activity. Such is the case, when you have a pager adapter.
Is the fragment going to be used in several activities?
The user input events will be reusable if you use a fragment.
Is the amount of communication between the fragment and the activity small?
If you need to pass big objects to the fragment, you would need to deal with the code that serializes them. Also, if you need to communicate between fragment and activity, you would probably need to implement interfaces. This, in most cases, adds complexity to your codebase. It's not a difference maker, but a criteria to take into account.
Google advises you to ALWAYS use Fragments.
Why? It's simple:
In the simplest case, Fragments are used like containers of activities.
Why do you need this? Again, it's simple.
Android 4 (ICS) supports both Smartphones and Tablets. This means the SAME application will be running on a smartphone and a tablet and they are likely to be very different.
Tablets have big screens which will be empty or unused - unless you assign it properly.
That means- Putting two fragments on one activity like Contact List and Contact Info.
The smatphone will display contact List, and on a touch- display the contact's Info.
On a tablet, the user will still see the list and the info will be next to it.
2 fragments- on one screen....
Smart? yes... supposed to be back compatible down to Android 1.6......
#############################################################
O.K, Already Knew That? then - just try to understand the case solved:
A lot of things work that way- list & details, Menus and Sub-Menus, Info, Detailed Info and some more detailed info.
You want a way to keep it natural and smooth for a tablet which you expect to preform that way, but can't expect smartphone to display it all like the tablet did...
Get it?
for more Information, check out this.
I really think you just need to catch the concept....
Historically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. Instead the object must be serialized or a globally accessible reference made available.
By making each screen a separate Fragment, this data passing headache is completely avoided. Fragments always exist within the context of a given Activity and can always access that Activity. By storing the information of interest within the Activity, the Fragment for each screen can simply access the object reference through the Activity.
https://softwareengineering.stackexchange.com/questions/244771/why-use-android-fragments
Fragment primary support more dynamic & Large UI Screen like Tablet.Because Tablet screen is much larger than normal Handset. There is more room to combine & Interchange UI Component.
Fragment allow such design without the need for such complex change in the View hierarchy.
By divide activity layout in fragment, we become able to modify activity's appearance at runtime
Edit:
The question is ultimately about if there are any defacto standards or Google recommendations on how to implement the below question.
Origin:
I have recently started to have a closer look at the Fragments concept in Android. I do get the idea of it (or at least I think I do) and I also see the need for it. I have no trouble understanding the technicalities behind the implementation of my fragments. What I seem to have problems understanding, though, is how to compose the final layout of my application, so that it automagically works on a large tablet as well as a small smartphone?
I have my list fragment (e.g. MS Outlook-inbox-list) and I have my detail view fragment (e.g. MS Outlook-email-preview). On a tablet I would naturally like to show these two fragments in a single activity, but on a smart phone I would like to show them in two different activities while there isn't necessarily room for both of them on a single activity.
How do I go about to solve this?
Do I have to implement three activities in my application (the all-in-one tablet activity and the two separate, smart-phone specific activities)? But how can the application then decide on which implementation to use (1 or 1+1)?
Usually my activities play the role of the 'controller' (according to the MVC paradigm) but, as of the above question, I would have three controllers. Which construction would play the role of the root controller? Should I write a 'master activity' (without UI) which programmaticaly tries to decide which device it lives on and then call the suitable fragments activity accordingly? But then; how can I - in a well defined manner - find out what type of device (tablet/handset) my application is running on?
I guess I could post some of my code but I don't think it would clarify my problem any further as it's more a question of architectural choices than implementation specific.
Cheers,
dbm
Do I have to implement three activities in my application (the all-in-one tablet activity and the two separate, smart-phone specific activities)?
No, probably only two. One is responsible for loading the ListFragment and, if there is room, the detail fragment. The other only loads the detail fragment -- this activity would be started by the first one if the user taps on a list entry and the detail fragment is not displayed by the first activity.
Usually my activities play the role of the 'controller' (according to the MVC paradigm) but, as of the above question, I would have three controllers.
IMHO, with fragments, the fragment is your controller. Activities are an orchestration layer determining which fragments are visible and handling cross-fragment events.
But then; how can I - in a well defined manner - find out what type of device (tablet/handset) my application is running on?
The simplest solution in many cases is to drive it by layout XML resources.
For example, in my above recommendation, the first activity could have two different versions of, say, main.xml. One (res/layout/main.xml) loads just the ListFragment. The other (say, res/layout-large-land/main.xml) loads the ListFragment and the detail fragment, or loads the ListFragment and a FrameLayout container for a dynamic detail fragment (one you would define via a FragmentTransaction). The activity itself determines whether it is managing two fragments or one by determining if the second fragment (or its FrameLayout "slot") exists in the inflated main.xml. That way, if you change your layout rules in the future (e.g., res/layout-sw600dp-land/main.xml), your Java code does not need to change.
There is nothing stopping you from using Configuration and DisplayMetrics to try to make decisions in the Java code as well.
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.