How to use Fragments - android

I'm trying to wrap my head around when exactly I should use Fragments and if I'm going to use them how to do so properly.
To my understanding Fragments should be used if you want a more flexible UI as it will be easier when rotating the device and easier to have your layout work with multiple screen sizes.
It seems to me that it is good to use them because you could have an app with ONE activity and multiple Fragments so the activity will be able to get calls from callbacks while the Fragments change what the user is seeing and interacting with. If I were to compare two apps, one made with Activities and the other with Fragments I would imagine to see something like this:
Activity app has a log in screen. The user can log in and it brings them to the main menu (New Activity). Once there they select the Friend button which brings them to a new Friend activity.
Fragment app has an Activity that loads the Log in Fragment into it's FrameLayout. The Log in Fragment allows the user to log into their account. Once it logged in, it replaces the Log in Fragment in the FrameLayout with the Main Menu Fragment. User presses Friend button, it opens the new Friend Fragment in the Activities FrameLayout. In this case all the work is being done in the Fragments but the Activity is just really holding them.
Please tell me why this is the incorrect use... or why this is correct.
Cheers

Take a look at the official Fragments doc. Short answer: always use Fragments. Fragments are better for reusability, flexibility, etc., etc.

Related

Why it is better to use DialogFragment for creating a dialog instead of an Activity class?

I am a beginner in android development. I am currently reading about Fragments from developer.android.com and this showed up about DialogFragment:
DialogFragment
Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity
class, because you can incorporate a fragment dialog into the back
stack of fragments managed by the activity, allowing the user to
return to a dismissed fragment.
Can anybody explain this to me ? Thanks
The fragment is lightweight and easy to implement. You need to style your activity to display a dialog. First, you have to understand the difference between activity and fragment.
Activity:
Activities have been around for a very long time and are used to
construct a single screen of your application. When someone is using
your Android application, the views that the user sees and interacts
with are hosted and controlled by a single activity. Much of your code
lives in these Activity classes, and there will typically be one
activity visible on the screen at a time.
Fragment
Fragments are another type of controller class that allows us to
separate components of our applications into reusable pieces.
Fragments must be hosted by an activity and an activity can host one
or more fragments at a time. A simple fragment looks similar to an activity, but has different life
cycle callback methods.
One of the original goals of the fragment concept was to help developers make applications that provide different user experiences on phones and tablets.
The canonical example of fragment use is an email client. Let’s take a look at the Gmail app. When running on a phone, the Gmail app will display a list of the user’s emails. Tapping on one of these emails will transition the screen to showing the detail view for that particular email. This process is composed of two separate screens.
For your Question:
It is always better to use dialog fragment instead of Activity. Because fragments are more customizable and easy to use. Light weight and gives reusability.
You can know more here:
http://www.informit.com/articles/article.aspx?p=2126865

Would it be better practice to use Fragments?

I am currently writing an Android app for my Masters final project. The app has two Activities and both have layouts corresponding to each activity. I also have a settings activity with settings fragment but I am not concerned about this one.
Activity A currently has a Spinner and a button which when pressed will do some stuff and then launch a Activity B. Activity B displays a chart, contains a couple of actions and a button to go back to Activity A.
Neither of these activities have Fragments currently but I am curious if it would be better to include Fragments. As far as I can tell using a Fragment wouldn't hinder performance so at this point it would be a cosmetic change.
Fragments are usually needed if you need to re-use some specific layout.
E.g--> If you have an app which displays movies, you can click and get movie details.
Here it would be better to use fragments as the layout would be the same for each movie and only the content would change inside.
In your case however, since there is not need for such frequent scenarios, you really do not need fragments.
If you want to change the content without changing your activity due to some actions of user, implementing UIs inside Fragments can be useful. Just set the the desired fragment inside Activity by using its FragmentManager. However, otherwise don't think about such change (shifting lots of code/layout from activities to fragments) in the code.

why must a fragment accompany a different activity

ActivityA launches fragmentA. I need to launch fragmentB. There are 2 ways of doing it, but I dont know which is the best way First way, create a ActivityB which would launch FragmentB. Therefore, ActivityA--> ActivityB--> FragmentB.
The second way, is just replacing FragmentA with FragmentB
Fragment b = AddRecordFragment.init(Integer.valueOf(f.getId()));
getFragmentManager().beginTransaction().replace(R.id.container,b).addToBackStack(null).commit();
When I took the Udacity course, they perferred the first way, but I cant see the logic in creating an second activity (activityB) for the mere purpose of launching an Fragment. Can you tell me what is the advantages and disadvantages to each ?
There really is no "right" way to do these kinds of things. There are recommended ways, there are best practices, there are common usages -- but all of this depends on what you, the developer, need to do to provide the best experience for your users and the best clarity and organization for fellow developers. Thinking through these things will give you the best answer for your particular scenario.
To address your particular question, think about what an Activity does, what its purpose is, and then think through why you would need Fragments. From the Android docs:
An Activity is an application component that provides a screen with
which users can interact in order to do something...
For Fragments:
A Fragment represents a behavior or a portion of user interface in an
Activity.
So already, even from the first sentence of each doc, we see a defined purpose for both components. An Activity is, well, an activity for the user. It's a screen with a purpose of allowing the user to DO SOMETHING. A Fragment, on the other hand, is a modular design that provides UI and other elements of interaction and data for the user that gets attached to an Activity. In other words, it helps the user do the thing that the Activity wants them to do, by either providing some point of interaction, or some visible form of data.
So now that we've clarified the purpose of these two components, ask yourself what the purpose of Activity B would be in your question. Will it provide the user with something new to do or see (even if through the use of Fragment B)? Will it provide something different from what the user was doing in Activity A? If so, then yes a new Activity is probably the best design choice. But if Fragment B is just another way of doing whatever it is the user is supposed to be doing in Activity A, or some sort of extension of that activity, then your best choice would be for Activity A to simply replace Fragment A with Fragment B itself through a FragmentTransaction.
The entire idea of working with fragments is to create a flexible design. Meaning you can use same view container to display different content with different functionality. So, it's clear that if you need to display a different fragment, you should replace it in the container.
In some cases you may prefer using a different activity, f.e. while launching settings, but if it's just a different content that can be contextualised with the same activity, definitely use fragment manager to replace in container.
It is not about the advantage, it is about what you want to do.
A Fragment represents a behavior or a portion of user interface in an
Activity
Now it if you want the Fragment to be a portion of the first activity you launch it the second way. That is
Fragment b = AddRecordFragment.init(Integer.valueOf(f.getId()));
getFragmentManager().beginTransaction().replace(R.id.container,b).addToBackStack(null).commit();
But if you want it to be a portion of the second activity you launch it the first way.
Depends on which activity the fragment should be a part of.

Is it a bad practice to have only one Activity in your Android app that uses fragments?

I'm wondering if this is a 'no no' in the Android community.
My app just has a MainActivity and uses a ViewPager and TabLayout to navigate across the fragments in the app.
The only problem I see is if the user presses the back button, it will exit the app and the app will not stay active like it would by pressing the home button.
Your thoughts?
Nice question bro,
Few months back I was thinking in sameway.
You are 100% right, you can do it without any trouble, it only depend on your project and what do you want to achieve.
You could control your fragments from a single activity, beacause all fragments are independent of each other.
The limitation is :
One fragment should never talk directly to another fragment, you have to go through the parent activity
Only some imp points are:
You need to learn all details about fragment.
You have to manage the order of the fragments.
It add lbit complexity in code
One Activity and all other Fragments

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