Confused about using Fragments in the app - android

I have a full-fledged app which is NOT developed using Fragments. My confusion is that should I change it to have Fragments instead of Activities. The thing that I would like to tell is that I'm using only portrait orientation in my application and it is built, keeping in mind only phones, not tablets. So my question is, will it do any good if I change the whole structure of app and use Fragments.
As far as I know, Fragments should be used only If we want to reuse something. Any suggestion is appreciated.

Fragments can be used to create a dynamic and multi-pane user interface, and as such are ideally suited for tablets which have a lot more screen real estate to use up. Of course, on a phone the situation is a little different, you have a much smaller space to play with and sometimes it can be a struggle just to get one Activity fitting onto the screen without worrying about including multiple Fragments.
Fragments are very good for dynamic interfaces, and for helping with compatibility between Tablet and Phone. They are also able to communicate with each other much better than Activities can, so there are certainly advantages to using them even on a phone-only setup. (See FragmentsManager for some functionality they can be used for)
One example of use is illustrated in the diagram below (taken from Android Developer site)
This illustrates the flexibility of the Fragments, which on tablet can occupy the same screen, switching to a more Activity-like format on a phone. It is this kind of power that gives the Fragment such an advantage over an Activity.
So clearly there are advantages to switching to a Fragment orientated solution in terms of flexibility, but your original question states that you are targeting phones only, and only in portrait orientation.
Having an application that is already in existence with Activities, providing that it is a solution that you are happy with, and has good usability I would say there was no reason to switch to Fragments (unless you are looking for a challenge or have some spare time and fancy a tinker). While advantages exist, a drastic change such as adding Fragments could introduce bugs into your application and impact the user experience (at least for the short term).
Long term, if you are ever considering bringing tablet support into the fold or would like to use the landscape orientation, then it might be a good idea to start looking at what you can do with Fragments to improve the experience, and integrate this with the current flow of your phone application.
Otherwise, the current solution you have created will more than suffice, and as long as it is well received by your customer base I see no reason to change.
Of course, there is no harm familiarising yourself with the Fragment APIs for future projects, or in the event that it is time for a refresh of your current project's UI.
It is worth pointing out that Fragments are only supported natively from Android 3.0 (API level 11), and to support earlier devices you will require the Android Support package found in your installation. As such, if your current application targets 2.x devices, I would stick with an Activity based approach, for simplicity and .apk size, unless moving to a native API Level (like Android 3.0+). This is personal preference though and ultimately the answer to your original question will boil down to your personal preference.

Think of fragments as a way to modularize your code into manageable pieces. Each fragment represents a small piece of functionality and UI. This allows your to easily adjust your code to fit different scenarios.
Sure you don't plan on supporting tablets now (regardless of how you feel tablet users will install the app), think of larger size 5-6" devices and the potential of extending your app over to them. It is best to provide your app to as many devices as possible and the best apps will tailor the experience to the device.
The transition to Fragments doesn't have to be difficult. Take a small piece of functionality and move it over to a Fragment. Then you will see how easy and flexible the new pattern is. You don't need to rewrite the entire application as Activities and Fragments can work together.
I believe by skipping out on Fragments you are really making your development tasks much more difficult in the long run.

If you don't plan to support tablets in the future than leave it as it is. You won't gain anything when you convert your app to fragments.
The situation is different if you start a new application. I would use fragments from the beginning in order to be more flexible should the need arise to support other form factors in the future. Note that the functionality is available in the support library so you can use it also on older devices.

It is easier to set interaction between fragments than between activities.
In case of activities:
You need to use startActivityForResult()/onActivityResult();
Your custom types must implement Parcelable interface in order to be passed between activities;
You have to free all resources when your activity is paused/stopped.
In case of fragments:
Passing data is as easy as getting an instance of fragment from FragmentManager and calling a method on it;
No need to implement Parcelable;
You can hold references to "heavy" resources in activity which contains all of your fragments and initialise/release them only once (no need for initialisation/release for each fragment).
Also, an instance of Fragment is more lightweight than instance of Activity and takes less time and resources to be initialised/resumed.
In general, interaction between the components of your UI is cleaner, more elegant, easier to implement when you use fragments.

As far as your application or any of the application is concerned , it's better to use fragments and it causes no harm to your application and it also ease your burden while further extending your application for tablets also.So, better to start with the use of fragments in your application.

I've just finished converting my application to use fragments, because:
Wanted a tablet version
Wanted to use ViewPageIndicator and ViewPager with advanced views
Those are the most compelling reasons to use fragments.
It might be a little more work, but with significantly more tablets appearing on the market and fast adoption rate, perhaps it's worth considering supporting tablets with a nicer UI?
If you really don't want to do this and have no requirement for view paging using advanced views then there is no point over-engineering your project to make it use fragments for using fragments sake. You could argue you might learn about them, but when you come to use them in your next project, you can learn then (that is what I did and it worked out fine).

Related

Why using Fragments?

I have read the documentation and some other questions' threads about this topic and I don't really feel convinced; I don't see clearly the limits of use of this technique.
Fragments are now seen as a Best Practice; every Activity should be basically a support for one or more Fragments and not call a layout directly.
Fragments are created in order to:
allow the Activity to use many fragments, to change between them, to reuse these units... ==> the Fragment is totally dependent to the Context of an activity , so if I need something generic that I can reuse and handle in many Activities, I can create my own custom layouts or Views ... I will not care about this additional Complexity Developing Layer that fragments would add.
a better handling to different resolution ==> OK for tablets/phones in case of long process that we can show two (or more) fragments in the same Activity in Tablets, and one by one in phones. But why would I use fragments always ?
handling callbacks to navigate between Fragments (i.e: if the user is Logged-in I show a fragment else I show another fragment). ===> Just try to see how many bugs facebook SDK Log-in have because of this, to understand that it is really (?) ...
considering that an Android Application is based on Activities... Adding another life cycles in the Activity would be better to design an Application... I mean the modules, the scenarios, the data management and the connectivity would be better designed, in that way. ===> This is an answer of someone who's used to see the Android SDK and Android Framework with a Fragments vision. I don't think it's wrong, but I am not sure it will give good results... And it is really abstract...
====> Why would I complicate my life, coding more, in using them always? else, why is it a best practice if it's just a tool for some cases? what are these cases?
I am sorry if I wrote too much, and thanks for your time. I hope I will get your attention, because I really need ideas and experiences about this topic.
Best regards, Ahmed
You shouldn't always use fragments. Fragments have their uses, such as when you want to page in and out parts of the screen or when you want to drastically change the UI in different orientations. When they make sense, use them. When they don't, skip them. I find they make sense in maybe about 10-20% of apps- I rarely see the need.
If there's a certain positive aspect apart from the simpler reuse of logic through different layouts, it's the ability of Fragments to be kept alive by the system at orientation change, aka while an Activity is reconstructed from zero, a Fragment can retain its instance, and therefore using them is more stable than an Activity. Also, switching between Fragments is quicker.
Personally, if I don't need to mess around with different orientations and layout sizes, I still prefer using Fragments and a singular container Activity around it, for stability and seamless switching between the different screens.
Its quite a general question and not directly related to a specific programming problem. But in my opinion good software is based on good design and therefore a good understanding and best practices. So your question is a good one for stackoverflow.
So, what about fragments. It took me a while to understand why you could or even should use them. As #pskink said, you can easily live without them. But if you are planning to rollout your software on different devices, you should definately think about fragments.
The screen resolution and density is not the only problem. Think about a smartphone. The screen is much smaller, so you can not present your app the same way as you can on a tablet. For instance a master detail flow. Left side, a list of elements and when you click one element, you will see details of that element on the right side. Easy to do on a tablet. But on a smartphone you would put the master-view into one fragment and the detail-view into another one.
You got two options to realize that scenario. Either programm different activities for smartphone and tablet but because they are actually doing the same logic, it's better practice to put the logic into fragments and reuse those fragments in two layouts (phone/tablet).

Two activities or two fragments?

In an Android app, I have two screens* the user sees, one for preparing a query and the other for displaying the results. The right UI here is to have the query preparation in one screen, and then see the result on the second screen. Since this app is aimed at phone users, there's no need to display the two at once.
The traditional Android way is to use two activities, a QueryPreparationActivity and a DisplayResultActivity, and switch between the two. However, I've been hearing more and more about how the Android UI is switching to fragments. I can implement the two screens as two fragments and have the activity switch them, but is it worth the trouble? I will essentially be reproducing the Activity management code Android already has.
Is there a reason to use two fragments here?
*I'm using the term screen, because it isn't necessarily an activity...
Personally, I always develop using Fragments.
But the best reason I can give you for using Fragments is when you develop for handset and tablet devices you get a lot of reusability.
I know you already mentioned that there is no need to show both screens at once. But say later you were to develop the same "screen" for a tablet device and realize that the preparation screen is too barren and want to have both queryprep and display result show at the same time, you would have to write a totally new 3rd activity.
If you used fragments, you would reuse your 1 activity and 2 fragments, and that activity should be coded smart enough to determine the size of the screen and show the proper layout.
Code Reusability & Flexibility are the buzz words here.
If you have any questions please leave a comment and I will expand my answer. If you like my answer, please upvote and accept.
Fragments were introduced encapsulate UI elements and related behaviour into a single, reusable module. Before fragments you had to re-write the much of the same code that 2 or more activities had in common especially if you couldn't find a good approach to abstract the UI/control code into a super class. This was further complicated by the limitations that activities only call setContentView once. So sharing some code between activities wasn't all that nice.
Now, to answer your question, it all depends on you. If you think that further down the road you could use the QueryPreparation or DisplayResult ui as a module (layout and logic behind it) then go for the fragment implementation. It could be a different layout for landscape view on phone or if you decide to support smaller tablets like the nexus 7. If you are sure that it will never happen then stick with activities. Personally, I use fragments everywhere and they are a sure way to "future proof" your implementation for reuse down the road.
In short Fragments were introduced to accommodate the emergence of tablet/large screen devices and allow developers to create applications that will run across a wide range of screen sizes with very little change to code.
More can be read here at the Android Blog. That blog also details some of the finer technical details for the reasons for the move toward Fragments. Also introduced at Goolge IO 2012 were DialogFragments which you should consider using instead of Dialogs. Another blog post here describes them.
You're better off getting used to using Fragments and DialogFragments from the get go as this is the way Android is moving. Only use individual Activities if you really really need to do a quick-and-dirty app for say testing purposes. Fragments, in my opinion, do require a bit more code-work to incorporate and to initially get your head round but it's worth the effort.

Android fragments when to introduce them into the application

I'm making an project that needs to run on tablets as well as phones.
I was thinking to use fragments for this. but i dont have any history in using them.
Should I implement them right away or is it easy to implement them later on?
( i could first make the working phone app and later on make it an tablet app)
someone with an history in implementing fragments for the first time?
I recommend to use fragments from the beginning for UI components which may be used in a master-detail like fashon on tablets but as single activity on the smaller phone. You will get a light overhead for the smaller phone (e.g. using an activity container exactly one fragment) but you will profit from that overhead when switching to the tablet. It will also improve a consistent UI design between smaller phones and tablets.
If you target pre-fragment (e.g. Android 2.x) devices use the support library. I also recomment to mark the classes depending on the support library using comments. This way you will find them easier when switching from the support library to the "native" implementation sometimes in the future (at least you have modify the import statements, because the support library uses different packages. In rare instance you will have to modify methods (e.g. change getSupportFragmentManager() to getFragmentManager()).
I have been working for two weeks to update an android application and make it using fragment, so it will be easier for you to use directly Fragment. But i think that the question that you must ask your self is did i need fragments in my app???
Essentially, Fragments allow you to show the user multiple 'activities' at one time. Did you need this?? if no it will be easier that you use resource qualifiers to point to another layout with more/less Fragments (ex. layout-land-large). You will be able to update the size of elements in your file.xml.
if you need to show two activities (when using tablet) , the best solution is using fragment. and here you say: Are the Fragments working together to provide the user a streamlined experience? If yes it will be perfect that you work directly with fragments because fragments send arguments between each other to communicate (not the same as activity).
In activity: intent.putExtra()
In fragment: you can use bundle for example. So if you need to update your application after you will waste your time searching for sender extras and sending it other wise.

Single Activity Application

I will try to keep this short, but I need some advice.
I work on a team that is developing applications for android, iphone, and wp7 in parallel.
We have a design team that comes up with a single design for all three platforms.
The latest application’s design is more marketing than productivity. The original POC for this app was done on the iphone. The design is very animation centric and most state changes are seamless (things will animate on and off the screen during state transitions).
If I keep developing against this design it means I will have to have everything in a single activity. So far, this has been a major headache. To my knowledge, dividing your application into activities is almost required. I could try to dynamically load and unload views as I change states but this doesn’t seem right.
I see where the design team is coming from where they want all these state changes to be seamless, but I don’t think this is right for android.
I would like to know what makes most sense. Should the design change to incorporate multiple activities or would it be worth trying to make this work.
We have a design team that comes up with a single design for all three platforms.
That's akin to coming up with a single floor plan to be applied to apartments, single family homes, and warehouses. The designers, or management, need to have their heads examined.
The latest application’s design is more marketing than productivity.
Did I mention that the designers, or management, need to have their heads examined?
If I keep developing against this design it means I will have to have everything in a single activity.
If I am interpreting your requirements correctly, that is probably accurate. While you can arrange for animations between activities, it is more of a "slide the old off, slide the new on", and I suspect that your requirements exceed that.
To my knowledge, dividing your application into activities is almost required.
It is certainly Android's intended development model for ordinary apps. However, games and the like may not follow this pattern, and you don't have to either.
I could try to dynamically load and unload views as I change states but this doesn’t seem right.
Depending on how many states there are, you might just hang onto all of them, recycling as you go.
I am surprised no one mentioned fragments which can be used instead of activities at many places.
Fragments can be seamlessly animated in and out or an activity.
You might want to take a look at subclassing ActivityGroup for your top-level activity. That can host multiple sub-activities. TabActivity, the only stock subclass of ActivityGroup, is perhaps not what you need because it includes a tab widget, but you can use it as inspiration for what you do need.
What specific headaches are you having with a single-activity architecture? Perhaps there are ways to make that less painful.
In general, if you are aiming to have native apps with a native look and feel, it is not reasonable to have a single UI design for all three platforms. The UI guidelines and user expectations for the systems are different, and those differences should be reflected in the UI designs.
If you really want to have a single UI for all platforms, just create a web app instead.
I'm not sure exactly what you mean by an "animation centric" design with seamless state changes. If you use multiple Activities, Android will animate between them in a way that Android users will expect. If you explain what exactly you are trying to accomplish, we can help you figure out if it makes sense in Android, and if so how to accomplish it.

Pattern "One activity, multiple views": Advantages and disadvantages

This pattern is similar to the pattern Main Servlet (the Front Controller) that is used for developing web applications.
The main idea of this pattern: we have one Activity that manages multiple views and this activity is responsible for representing current content. Not all views need functional of activity (e.g. life-cycle methods) so the main question is: if I can go without activity why do I have to use it?
I have found the following disadvantages of using this pattern:
Official source doesn't recommend to Overload a Single Activity Screen
but they don't explain why.
We cannot use TabActivity, ListActivity, MapActivity. But there are some tricks to go without them.
If different screens have different menu it's a problem to make that without activities.
It is necessary to keep history by ourselves. But it's not so difficult to develop.
I have found the following advantages of using this pattern:
It's faster to change the content of current activity than to start another activity
We are free to manage history as we want
If we have only one activity-context it's simpler to find and solve problems with memory leaks
What do you think about this pattern ? Could you provide any other advantages/disadvantages ?
We cannot use TabActivity, ListAcivity, MapActivity. But there are some tricks to go without them.
You have to use MapActivity if you want to use MapView. You have to use PreferenceActivity if you want to use preference XML.
It is necessary to keep history by ourselves. But it's not so difficult to develop.
The difficulty in managing your own history will depend greatly on what the history needs to be. Implementing history for a simple wizard will be fairly easy. However, that is a particularly simple scenario. There is a fair amount of history management code in Android that you would have to rewrite for arbitrary other cases.
You also forgot:
#5. You will be prone to leak memory, because you will forget to clean up stuff, and Android will not clean up stuff (since it assumes that you will be using many small activities, the way they recommend).
#6. Your state management for configuration changes (rotation, dock, SIM change, locale change, multiple displays, font scale) will be more complicated because now you also have to figure out what extra stuff (e.g., history) need to be part of the state, and you have deal with all of them at once rather than activity-at-a-time.
#7. Having multiple entry points for your application becomes more challenging (e.g., multiple icons in launcher, app widget linking to some activity other than the main one, responding to etc.).
It's faster to change the content of current activity than to start another activity
For most modern Android devices, the speed difference will not be significant to most users, IMHO.
If we have only one activity-context it's simpler to find and solve problems with memory leaks
Except that you still have more than "one activity-context". Remember: your activity, large or small, is still destroyed and recreated on configuration changes.
What do you think about this pattern ?
Coase's "nature of the firm" theory says that businesses expand until the transaction costs for doing things internally become higher than the transaction costs for having other firms do the same things.
Murphy's "nature of the activity" theory says that the activity expands until the transaction costs of doing things internally become higher than the transaction costs for having other activities do the same things. Android developers will tend towards a "user transaction" model for activities -- things that are tightly coupled (e.g., steps in a wizard) will tend to be handled in single activity, and things that have little relationship (e.g., browse vs. search vs. settings vs. help vs. about) will tend to be handled in distinct activities.
This will be horrible to maintain if new functionality is added later on.
I'm also not convinced it will be so much faster that the user could notice.
Having components as smaller pieces that are easier to change or swap out is definitely the way to go.

Categories

Resources