Activity vs Fragment - android

I am learning android from two resources one from video and one from book +(android developer resources ). Both show how to have multiple views in a different ways. Video one used activity and intent book used fragments. What is the best practice fragment/activity?When to use Activity and when to use Fragment.

You will most likely hear things like
You can have an Activity without a Fragment but you cannot have a Fragment without Activity
You can have multiple Fragments under a single Activity
You can use Fragments to have multiple sections in a single screen
Fragments has its own lifecycle
So I'd give my personal thought and a little bit of scenario based on my own experience on how I would decide which to use based on a given scenario.
Consider a Registration Form where I'm required to create 3 screen features of which contains Basic Personal Info, Financial Information and Online Mailing Information, in this case I would use multiple Fragments under 1 hosting Activity named RegistrationActivity.
Now consider same application where I'm required to create a User Setting Screen it wouldn't make sense if I create another Fragment under that same Activity right?, so that would be a separate context and everything about it will go to another Activity named SettingsActivity
There are more technical things under the hood, but most of the time you will decide which to use based on the use-case you are dealing with.
There is also an up to date architecture namely Modular design where each closely related components are grouped inside a module library, majority of such project will fall under the feature category where most of the time if not all, have single Activity hosting multiple fragments. And going back to my scenario it would be like a Registration Module
Hope it make sense.
Have a look at another similar post
Why fragments, and when to use fragments instead of activities?

Related

When and how to prevent a god activity in Android

I know this question might not be one which has just one correct answer. But letting me know, that there are several solutions with good reasons for each of them, would already help a lot. So here we go:
I have designed an app which manages persons along with measurement data for each person. The data can be displayed in a chart. Generally this leads to the following tasks:
Person: Add
Person: View
Person: Edit
Person: Delete (more an option with a security dialog than a real screen)
Measurements: View (List)
Measurement: Add
Measurement: Delete (again more an option with a security dialog)
Measurements: Plot (in a large graph view)
The app will run on a phone at first. I have read that an activity is supposed to serve a very limited purpose, so the scenario would lead to one activity for each task.
However, when the app is displayed on a tablet in landscape mode, I can imagine to have three sections on the screen at once:
One section in the top right cornern managing persons
One section below that listing the values for the selected person
One larger section on the right part of the screen to plot measurements
I often read that I should avoid to create god activities. On the other hand I read that fragments is the way to go, so that each screen can easily be displayed as a subscreen on a tablet, as it is planned here.
I started off with creating the app for mobile phones, so I created one activity, which juggles all fragments (almost one for each task) in a single fragment container.
Is this the way to go, when I want to do it by the book?
I was wondering whether I should create a separate activity for each task. For the phone this makes things easier. But on a tablet I would have to control the fragments from one single activity anyway, correct? So in that case a god activity it needs to be?
You are definitely on the right track, but there are some things you may want to look into.
In my opinion Activities should only be used to host Fragments and transfer events between Fragments. Basically, the only logic that you should have in your Activity is handling the navigation. The logic stays in the Fragments (or some other layer, used by your Fragments) and it is not exposed to the Activity at all. In that way there will be no need to duplicate any logic and make some Activity a "God" Activity.
Good that you started thinking about it. You should always prevent god activity. Read about MVC, MVP & android architecture patterns which help you avoid creating a god object.

One activity - many fragments OR many activities - many fragments?

I'm planing a new app with a navigation drawer.
It is better to use one activity which manage many fragments or to use many activities with many fragments? Are there any serious advantages or disadvantages?
I read many articles about this but there are from 2012 and older.
(I'm just planing to read and insert some datas into/from the database..)
From my experience I would recommend rather having multiple activities with many fragments. If you use a single activity you are going to find it harder and harder to manage fragments with the activity lifecycle.
For example if the activity is destroyed (e.g. if phone is low on memory and user receives a phone call or you call an intent to open the camera), when the intent is recreated you will need to handle recreating the fragments and their states.
With a single activity this can quickly become a nightmare to manage if not done carefully. With multiple activities it's easier to manage and helps seperate portions of the app - making it easier to debug as well.
An example of how something simple can become complex with a single activity would be something such as the back button.
If you need to handle it different for different fragments that means your activity is going to need to cater for which fragment is currently visible, as the activity overrides the backbutton, not the fragment. This also would likely mean you need to add interfaces to notify the fragments of a back button press.
Stating all of this however, there are some apps that benefit from a single activity. For example if you have a viewpager for swiping fragments (e.g. pages of a book) or fragments that do little interaction, then a single activity can be beneficial.

Proper usage for Activities in Android

From what I understand, and activity is equivalent to a "page" in a web app.
For example, the list view would be one activity, edit view another activity, and add view a third activity.
While this works as expected, android activities seem to operate as individual apps--the action bar is different for each activity and so are the menus.
Is my usage of activities above correct or should I be using some other mechanism such as swapping out layouts and views?
Fragments are a core part of activities - not that much different. The use of fragments comes since Honeycomb 3.0 and the idea is an option to split the screen in several fragments at once. For example if you look at the gmail app for a tablet - you have one fragment on the left dealing with navigation and then the next fragment on the right is the list of emails.
On a mobile device, viewing area is limited, so you it could be said that fragments sort of behave like an activity - you interact with one fragment, which triggers another and so on and so fort. But in the end you always reference a super activity of each of these fragments - for example when you want to access the context.
So if you just want to wrap web pages in WebViews, stick with activities. If your scenario might involve developing for both tablets and phones, then go for the fragments.
Alternatively, you can read about the design philosophies of both here:
http://developer.android.com/guide/components/fragments.html
Good luck!
Fragments are to be used when you have common feature across multiple activities. From my perspective you should use individual activities as there will be back-end code to support (fetch and validate data, i.e. business logic). This way you have more modular code. Fragments is a new feature from v3.0.
From what I know, Fragments would be a good option to be able use different configurations/real estates on different devices. For example, if you are on a device with big real estate like Tablets or TVs you can display more content in a single activity, on the other hand for a devices with smaller real estate you can show content based on a progressive manner.
See this: http://developer.android.com/training/multiscreen/adaptui.html
Note that Fragments are supported only on devices running Android 3.0, so you might have to use Support Fragments (See: https://stackoverflow.com/a/6528757/713778)
But Again it depends on your specific needs. I am not sure what your exact use case is, but I would suggest you to watch some Android design in Action for some examples to improve your design and make your app "User Centric" (See: https://www.youtube.com/playlist?list=PLWz5rJ2EKKc8j2B95zGMb8muZvrIy-wcF)
I recently came across this https://www.youtube.com/playlist?list=PLWz5rJ2EKKc-riD21lnOjVYBqSkNII3_k seems provide an in-depth analysis on User Experience.
I would recommend using fragment for web like views. Fragments are pretty snappy compared to activities and reusable.
But before you start, make sure to fragments are good fit for your requirements since they are supported from android 3.0.
You can declare fragments from xml itself or you can create frame layout and add that view in the code itself.
http://www.c-sharpcorner.com/UploadFile/2fd686/fragments/
The above link has a good example tabhost.

Are android fragments like iframe in HTML?

I understand that android is a completely different thing than browser programming.
But coming from a web development background, I wanted to undertand what fragments are supposed to be used for ?
Are they similar to the concept of iframes in an HTML page having its own UI and can be added to any other page?
If not then what is tje general use-case of android fragments ?
They are reusable parts of your applications. You can have for example two different Activities using same Fragment. You may want to read Fragments Design Philosophy in the android documentation.
Here's also short description from the same documentation page:
A Fragment represents a behavior or a portion of user interface in an
Activity. You can combine multiple fragments in a single activity to
build a multi-pane UI and reuse a fragment in multiple activities. You
can think of a fragment as a modular section of an activity, which has
its own lifecycle, receives its own input events, and which you can
add or remove while the activity is running (sort of like a "sub
activity" that you can reuse in different activities).
Yes, I think you can think of them as the same at a conceptual level.

How Fragments affect the Activity "single, focused thing that the user can do" principle?

As Android documentation states: "An activity is a single, focused thing that the user can do."
However with Fragments we will be able to do many "things" within the same Activity as Reto Meier suggest. His suggestion is to replace a selection fragment by a content fragment within the same Activity (section "Within our code this produces a dilemma").
Lets say my application is a "bit" more complex, with many activities, with a complex navigation tree and designed with the "single, focused thing that the user can do" principle in mind.
Lets say now I have to adapt it to Fragments and large screens... and that I don't want to create a second application, neither have two completely different logics (one for phones other for tables) inside one application.
Should I have one Activity to manage all the application fragments and fragment transactions? Like Retro Meier suggest above. Is that the recommended path to follow? Thus breaking with the "single, focused thing that the user can do" principle for Activities?
Or am I missing something? I hope ;)
BTW, I think Fragments looks great, but from what I have seen till now, only if you are creating an application from the scratch. Because making applications to be compatible with phone and tablet looks like going to be a bit tedious. Hope to be wrong :)
Dianne Hackborn already has answered (thx for the link mgv):
you could put your entire application in one activity in which you change the fragment structure as its state changes
So then Activity becomes a sort of container where you will be able to plug Fragments. I like the approach, but... in my app there are about 30 different operations available, each one requires about 2 to 4 screens steps to be performed(forms and selection lists), all of them differ and there are also navigation restrictions. It works fine with Activities each one handling one screen/step behaviour.
So then to port to Fragments I should move each screen logic to Fragments and use Activities as containers for each operation. Thus leaving Activities as the ones managing the navigation between Fragments for every operation, right? Looks like going to be a pain to adapt long applications. :(
Current Activity definition should change a bit btw. :)
Should I have one Activity to manage all the application fragments and fragment transactions?
That is impossible to answer in the abstract. However, most applications will have multiple activities, even in a fragment-based world. Some of that will be to accommodate smaller screen sizes, where it will tend to be one fragment per activity. Some of that will be required by the framework (e.g., inheriting from PreferenceActivity). And, some of that will be by GUI design.
Thus breaking with the "single, focused thing that the user can do" principle for Activities?
That portion of the documentation was written in 2008, perhaps earlier. Had fragments existed back then, I imagine the documentation would state that a fragment is a "single, focused thing that the user can do", with activities serving as an orchestration layer, determining what fragments are visible in what circumstances.
The documentation will not in all places be updated to reflect fragments, and even if it does, it will take some time. For the balance of 2011, at minimum, you will need to perform your own translations of 2008-era instructions to convert them to 2011-era fragment-based UIs.
Lets say now I have to adapt it to Fragments and large screens... and that I don't want to create a second application, neither have two completely different logics (one for phones other for tables) inside one application.
I have no idea what you consider "completely different logics" to be. In a fragment-based app, most of your business logic will be in the fragments themselves. The activities, again, serve as an orchestration layer, determining what fragments should be visible and coordinating event handling. The latter will get a bit more complicated than it used to be, since sometimes clicking on an item in a list will bring up a new fragment and sometimes clicking on an item in a list will start a new activity, depending on screen size.
Or am I missing something?
To be honest, you are missing enough concreteness to your question to make it reasonably answerable.

Categories

Resources