All the reasons I can find for using Fragments in Android activities have to do with having the ability to display multiple classes/view in the same screen, encapsulating multiple logical components, etc.
Considering all this, it seems, fragments are only actually useful when you employ the use of many of them.
Is that so? Is there ever a point of using just one fragment in an activity?
I ask now because I saw an option on Android Studio to do just that, and I am wondering what the point is.
Out of my personal opinion, I would say yes.
For the following reasons:
Assuming you are familiar with Fragments, creating a Fragment is hardly any extra work plus has the following benefits
Fragments can easily be reused somewhere else (possibly another Activity that has more Fragments, furthermore, Fragments do not necessarily need to use up the full screen).
Activity transitions are more expensive, Fragment transitions are more sophisticated.
The Fragment animation framework is better (in terms of usability and performance).
I always like to keep the number of Activities to a minimum which keeps the AndroidManifest.xml short and clean.
UI separated into Fragments leads to cleaner code structure and easier code maintenance.
According to google coding guidelines, it is best practice to create as few Activities as possible, and create multiple Fragments instead that are switched inside an Activity.
Well it depends, if you are going to use that fragment in another activity yea, you have a "point" and maybe in a future you can reuse it on another activity, but in the case for example of a splash screen well, it don't have a point. All depend in the uses you want to give to your application.
Pros:
-> reusable piece of code
easy to utilize it again in any module
easy to debug
-> handles orientation changes better than activity using setRetainInstance(true)
-> great help when scale the app in future for multipane layouts or multi-screen support
Cons:
-> little overhead and time consuming if you are not familiar with fragments
Related
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).
My doubt here is how to achieve a clean and easy code to maintain over time in an Android app?, I'm trying to apply Uncle bob - clean code rules but as I keep going with development sometimes some rules must be broken, and I end with an Activity of 700 lines (I'm not using Fragment, and 700 lines seems to be a Class that "does too much things") so I want to know if someone has try an Android app with proper use of Fragment and could answer these questions:
1- does it really impact on Activity lines length (at least less than 300-500 [not strictly this numbers but a "reasonable" Class length] lines)?
2- does code keep clean and easy over the time?, not necessary with Uncle bob rules but considering best practice in OO while coding.
3- does it have a considerable impact in terms of "Performance"?
4- does Fragment help to support in a more simple way a wide fan of Screens?"
5- ignoring developer skills, what "should" be the way to go non-Fragment activities or activities with rich Fragment use?
Note: this is not an attemp of Duplication to Android - Activity vs FragmentActivity? since the topic here is not about tab format but best practice for android development.
sorry for my english ;).
You are conflating the use of fragments with the use of FragmentActivity.
FragmentActivity is a subclass of Activity designed for use with the backport of fragments from the Android Support package. You usually only use FragmentActivity if you are using the backport. If you are using fragments, but your android:minSdkVersion is set to 11 or higher, you can usually skip FragmentActivity.
With that in mind:
does it really impact on Activity lines length (at least less than 300 lines)?
That is impossible to say. It is equivalent to asking whether a Restaurant that subclasses Business will be longer or shorter than a Restaurant that subclasses FoodSupplier. It all depends on your code.
That being said, it is certainly possible that the use of fragments will reduce the lines of code in the activity. IMHO, that's not a good reason to use fragments.
does code keep clean and easy over the time?, not necessary with Uncle bob rules but considering best practice in OO while coding.
That is impossible to say. It is equivalent to asking whether a Restaurant that subclasses Business will be "clean and easy" compared to a Restaurant that subclasses FoodSupplier. It all depends on your code.
does it have a considerable impact in terms of "Performance"?
Not usually.
does Fragment help to support in a more simple way a wide fan of Screens?"
If by "wide fan of screens", you mean "a wide range of screen sizes", then yes, fragments can help with that. In fact, that's the #1 reason for using fragments, IMHO. However, fragments alone do not magically help with screen sizes, any more than having capital letters in method names magically helps with screen sizes.
ignoring developer skills, what "should" be the way to go FragmentActivity or Activity?
As stated previously, you usually only use FragmentActivity if you are using the backport of fragments. If you are using fragments, but your android:minSdkVersion is set to 11 or higher, you can usually skip FragmentActivity.
If your question really is "should I be using fragments in my app?", the answer is "probably, but it depends upon the app".
Yes, fragments are the way to go. They help spread your code around in a logical way so you don't have a 700 line activity, they keep your code easy because each fragment will have its own class usually, and they do, to answer your 4th question, make it easy to have "A wide fan of Screens".
I recommend this video to help get you started. For any beginners, this video is a great explanation of how to use fragments ( I know because I had a hard time figuring out how to use them until I watched this video). It is called "Programming Android with Fragments" by Andrew Ruffolo:
http://www.youtube.com/watch?v=KyXvq_kwfzg
This video demonstrates the power of fragments. You still need a main activity of some kind, but this main activity acts kind of like a container for the fragments, and most of the functionality of your app is handled by the fragments and their corresponding classes.
I have never used activities because I started app development after fragments were added to android, but it seems like fragments help break down your app in the same way that methods and inner classes help break down your classes, and the same way that classes help break down a project or program. I am not sure if this was possible or as simple using only activities before fragments were added.
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.
I read the fragments tutorial, but I still don't understand why they are actually needed. The tutorial gives the example of the 2 fragments in a wide screen and 2 activities in a small one, but I actually could just use a view and put it in the same activity or in another activity to achieve the same effect, so what does a fragment give me that a simple view doesn't? Thanks.
A fragment has a life cycle of its own , so you don't have to worry about memory and objects in larger screens where this does matter.
They're suitable when you want to put different content for different types of layouts. Mainly for building an app that's suited to both tablets and phones.
Think of a Fragment like a different activity within the same screen. Sometimes it's easier to have the code itself to be controlled within the fragment, rather than in a master Activity, especially if you intend to split them into separate layouts.
Things like Fragment dialogs are also more powerful than classic Dialogs. Communicating information to a fragment is a little easier and more efficient than between activities (though this may vary according to situation).
If you don't have a reason to use them or don't feel like experimenting, go as simple as possible. There's quite a bit of overhead to Fragments, so unless you're designing for multiple layouts (mainly tablets), it's more work for little gain.
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.