Android - relationship between Fragment and Activity - android

my question is really simple: can I create/start a Fragment from an Activity, and vice versa? And how can I do that?
I need to implement this for my app, and I read discordant opinions on the web. Some say that you can only open fragments from other fragments, other say that it's possible but you shouldn't do that, instead you should open fragments only from activities. I'm a bit confused.
I found different ways to do one thing or another, but none worked. The only thing that worked for me was create an Activity from an Activity. What I need to do is to start an Activity from a Fragment, or a Fragment from a Fragment.
Before doing any kind of re-implementation I'd like to understand what of this can actually work, and why the other not.
Thanks everyone, any hint is welcome.

Fragments have been introduced since Android Honeycomb (3.0) and are a very important concept in developing and designing your apps.
To answer your questions, you can start a fragment from your activity and you can also start activities from your fragments. You can also start fragments from other fragments. You can use them to make your code much more adaptable by replacing them in tab layouts, or master-detail layouts.
There's a lot to read and understand on using fragments and implementing them into your app, so I suggest you read the Android documentation on fragments.

Fragments are placed inside activities and their life cycle is heavily tied to the life cycle of the containing activity.
As for "opening" fragments. Are you talking about adding fragments? You can add fragments to activities via code or XML and you can add fragments to fragments (nested fragments).
Launching an activity is possible either way - from fragments or from activities - via intents.

Fragment: typically represents a reusable portion of an activity's user interface, but may also represent reusable program logic. You can combine several fragment to create the user interface that make better use of your phone or tablet.
you can easily interchange fragments to make your GUI'S more dynamic.
Fragment must be hosted by an activity and they can not execute independently.
Fragment they have their own life cycle which mean they can start an app.
for example: they have onCreate() method so the fragment can add their own menu items to host an activity menu.

Related

Show two Activities inside an Activity

I have two different Activities, and I want to show them both at the same time in another Activity. Is there any way to do that?
Thanks in advance!
its not possible , You have to use Fragments to do so...
convert those two Activities to Fragments and create a Activity and place those Fragments in Activity.
Ref :
http://developer.android.com/reference/android/app/Fragment.html
http://developer.android.com/guide/components/fragments.html
Yes, it is possible with ActivityView in android. There is no proper documentation that is available on the internet. but if you can check the android source code you can able to find the code related to ActivityView. Android is using the ActivityView for its car launcher applications.
check out below links:
google implementation of ActivityView.java
you can find the ActivityView.java usage examples
here
and here
Yes there is a way ! You cannot display 2 activity inside one, you have to use fragments !
A fragment is an independent component which can be used by an activity. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts.
A fragment runs in the context of an activity, but has its own life cycle and typically its own user interface. It is also possible to define fragments without an user interface, i.e., headless fragments.
Fragments can be dynamically or statically added to an activity.
You'll find the answers of all of your questions about fragments on this link
Hope it's been helpfull =)
Fragments and FragmentActivity comes into play here. Make your two activities separately as two different fragments, And attach these two fragments into a FragmentActivity. So that in a single screen you can view two activites(Here its a fragment).
You can also try using ViewPager concept it may suits to your scenario.
Download the sample here,
http://developer.android.com/training/animation/screen-slide.html

Activity or Fragment?

I'm new in Android programming, researching and reading Android's manuals I've seen that you can use activities and fragments. I've understood that a fragment is a ¨small activity¨.
For example, I can create an app with buttons that create new activities or I can create an app with only one activity that open a ¨main¨ fragment with buttons that replace that with another.
So my questions are: when is more convenient to use one or another? Can I get the same functionality?
Another final question: I want my app to have a drawer similar to the Facebook app, is it a Fragment or a regular drawer with an effect?
Thanks a lot
You actually use both. A fragment cannot live without a hosting activity.
As as simple rule of thumb, use fragments everywhere that has a reusable or pluggable interface. Use activity on simple places that does not call for a fragment, such as splash screens.
For the facebook drawer thingy, this is it -> https://developer.android.com/design/patterns/navigation-drawer.html
Fragments sit inside of activities so really you have to use just activities or both fragments and activities. I would use fragments.
You really need to read this until you understand it a bit more
https://developer.android.com/guide/components/fragments.html

One Fragment per Activity

I know this question will probably get closed very quickly as its largely opinion based but I have little experience using Android and could do with some guidance.
I have built an App and every Activity only hosts one fragment, and I have around 10 activities overall, meaning I also have 10 fragments.
Is it bad practice to just have one fragment being hosted by each activity as I know an activity can host multiple fragments? Should I use one or two activities that host multiple fragments or is the way I currently do it okay?
The purpose of Fragment is to use/reuse an area/portion inside an Activity. In your current design, you don't really need fragments at all, because whatever being shown on fragment can directly be shown in your 10 activities.
However, if you want, you may use single Activity and host a fragment (out of your 10 fragments) depending on the selection/criteria.
From the Android Docs: http://developer.android.com/guide/components/fragments.html
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).
So if you are reusing components in the various activities, then it may be advisable to create a few fragments that can swapped in and out, instead of having everything in so many activities. Also, if you plan on supporting multiple screens/devices it tends to be easier by having fewer activities and making use of reusable fragments.

Dilemma: when to use Fragments vs Activities:

I know that Activities are designed to represent a single screen of my application, while Fragments are designed to be reusable UI layouts with logic embedded inside of them.
Until not long ago, I developed an application as it said that they should be developed.
I created an Activity to represent a screen of my application and used Fragments for ViewPager or Google Maps. I rarely created a ListFragment or other UI that can be reused several times.
Recently I stumbled on a project that contains only 2 Activities one is a SettingsActivity and other one is the MainActivity. The layout of the MainActivity is populated with many hidden full screen UI fragments and only one is shown. In the Activity logic there are many FragmentTransitions between the different screens of the application.
What I like about this approach is that because the application uses an ActionBar, it stays intact and does not move with the screen switching animation, which is what happens with Activity switching. This give a more fluent feel to those screen transitions.
So I guess what I'm asking is to share your current development manner regarding this topic, I know it might look like an opinion based question at first look but I look at it as an Android design and architecture question... Not really an opinion based one.
UPDATE (01.05.2014): Following this presentation by Eric Burke from Square, (which I have to say is a great presentation with a lot of useful tools for android developers. And I am not related in any way to Square)
http://www.infoq.com/presentations/Android-Design/
From my personal experience over the past few months, I found that the best way to construct my applications is to create groups of fragments that come to represent a flow in the application and present all those fragments in one Activity. So basically you will have the same number of Activities in your application as the number of flows.
That way the action bar stays intact on all the flow's screens, but is being recreated on changing a flow which makes a lot of sense. As Eric Burke states and as I have come to realize as well, the philosophy of using as few Activities as possible is not applicable for all situations because it creates a mess in what he calls the "God" activity.
Experts will tell you: "When I see the UI, I will know whether to use an Activity or a Fragment". In the beginning this will not have any sense, but in time, you will actually be able to tell if you need Fragment or not.
There is a good practice I found very helpful for me. It occurred to me while I was trying to explain something to my daughter.
Namely, imagine a box which represents a screen. Can you load another screen in this box? If you use a new box, will you have to copy multiple items from the 1st box? If the answer is Yes, then you should use Fragments, because the root Activity can hold all duplicated elements to save you time in creating them, and you can simply replace parts of the box.
But don't forget that you always need a box container (Activity) or your parts will be dispersed. So one box with parts inside.
Take care not to misuse the box. Android UX experts advise (you can find them on YouTube) when we should explicitly load another Activity, instead to use a Fragment (like when we deal with the Navigation Drawer which has categories). Once you feel comfortable with Fragments, you can watch all their videos. Even more they are mandatory material.
Can you right now look at your UI and figure out if you need an Activity or a Fragment? Did you get a new perspective? I think you did.
My philosophy is this:
Create an activity only if it's absolutely absolutely required. With the back stack made available for committing bunch of fragment transactions, I try to create as few activities in my app as possible. Also, communicating between various fragments is much easier than sending data back and forth between activities.
Activity transitions are expensive, right? At least I believe so - since the old activity has to be destroyed/paused/stopped, pushed onto the stack, and then the new activity has to be created/started/resumed.
It's just my philosophy since fragments were introduced.
Well, according to Google's lectures (maybe here, I don't remember) , you should consider using Fragments whenever it's possible, as it makes your code easier to maintain and control.
However, I think that on some cases it can get too complex, as the activity that hosts the fragments need to navigate/communicate between them.
I think you should decide by yourself what's best for you. It's usually not that hard to convert an activity to a fragment and vice versa.
I've created a post about this dillema here, if you wish to read some further.
Since Jetpack, Single-Activity app is the preferred architecture. Usefull especially with the Navigation Architecture Component.
source
Why I prefer Fragment over Activity in ALL CASES.
Activity is expensive. In Fragment, views and property states are separated - whenever a fragment is in backstack, its views will be destroyed. So you can stack much more Fragments than Activity.
Backstack manipulation. With FragmentManager, it's easy to clear all the Fragments, insert more than on Fragments and etcs. But for Activity, it will be a nightmare to manipulate those stuff.
A much predictable lifecycle. As long as the host Activity is not recycled. the Fragments in the backstack will not be recycled. So it's possible to use FragmentManager::getFragments() to find specific Fragment (not encouraged).
In my opinion it's not really relevant. The key factor to consider is
how often are you gonna reuse parts of the UI (menus for example),
is the app also for tablets?
The main use of fragments is to build multipane activities, which makes it perfect for Tablet/Phone responsive apps.
Don't forget that an activity is application's block/component which can be shared and started through Intent! So each activity in your application should solve only one kind of task. If you have only one task in your application then I think you need only one activity and many fragments if needed. Of course you can reuse fragments in future activities which solve another tasks. This approach will be clear and logical separation of tasks. And you no need to maintain one activity with different intent filter parameters for different sets of fragments. You define tasks at the design stage of the development process based on requirements.
There's more to this than you realize, you have to remember than an activity that is launched does not implicitly destroy the calling activity. Sure, you can set it up such that your user clicks a button to go to a page, you start that page's activity and destroy the current one. This causes a lot of overhead. The best guide I can give you is:
** Start a new activity only if it makes sense to have the main activity and this one open at the same time (think of multiple windows).
A great example of when it makes sense to have multiple activities is Google Drive. The main activity provides a file explorer. When a file is opened, a new activity is launched to view that file. You can press the recent apps button which will allow you to go back to the browser without closing the opened document, then perhaps even open another document in parallel to the first.
Thing I did: Using less fragment when possible. Unfortunately, it's possible in almost case. So, I end up with a lot of fragments and a little of activities.
Some drawbacks I've realized:
ActionBar & Menu: When 2 fragment has different title, menu, that
will hard to handle. Ex: when adding new fragment, you can change action bar title, but when pop it from backstack there is no way to restore the old title. You may need an Toolbar in every fragment for this case, but let believe me, that will spend you more time.
When we need startForResult, activity has but fragment hasn't.
Don't have transition animation by default
My solution for this is using an Activity to wrap a fragment inside. So we have separate action bar, menu, startActivityForResult, animation,...
The one big advantage of a fragment over activity is that , the code which is used for fragment can be used for different activities. So, it provides re-usability of code in application development.
use one activity per application to provide base for fragment
use fragment for screen ,
fragments are lite weight as compared to activites
fragments are reusable
fragments are better suited for app which support both phone & tablet
You are free to use one of those.
Basically, you have to evaluate which is the best one to your app. Think about how you will manage the business flow and how to store/manage data preferences.
Think about, how Fragments store garbage data. When you implement the fragment, you have a activity root to fill with fragment(s). So, if your trying to implement a lot of activities with too much fragments, you have to consider performance on your app, coz you're manipulating (coarsely speaks) two context lifecycle, remember the complexity.
Remember: should I use fragments? Why shouldn't I?
regards.
I use Fragments for better user experience. For example if you have a Button and you want to run let's say a webservice when you click it, I attach a Fragment to the parent Activity.
if (id == R.id.forecast) {
ForecastFragment forecastFragment = new ForecastFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_content, forecastFragment);
ft.addToBackStack("backstack");
forecastFragment.setArguments(b);
ft.commit();
}
In that way the user won't have to move in another activity.
And secondly I prefer Fragments because you can handle them easily during rotation.
It depends what you want to build really. For example the navigation drawer uses fragments. Tabs use fragments as well. Another good implementation,is where you have a listview. When you rotate the phone and click a row the activity is shown in the remaining half of the screen. Personally,I use fragments and fragment dialogs,as it is more professional. Plus they are handled easier in rotation.
Almost always use fragments. If you know that the app you are building will remain very small, the extra effort of using fragments may not be worth it, so they can be left out. For larger apps, the complexity introduced is offset by the flexibility fragments provide, making it easier to justify having them in the project.
Some people are very opposed to the additional complexity involved with fragments and their lifecycles, so they never use them in their projects. An issue with this approach is that there are several APIs in Android that rely on fragments, such as ViewPager and the Jetpack Navigation library. If you need to use these options in your app, then you must use fragments to get their benefits.
Excerpt From: Kristin Marsicano. “Android Programming: The Big Nerd Ranch Guide, 4th Edition.” Apple Books.
Some wrong ideas:
Always put an activity in your app and handle different screens with fragments.
Write the UI code directly in the activity.
Handle navigating between screens (I don't mean tabs, I mean for example full-screen views) by fragments.
Activities can be replaced by fragments.
Here is the thing!
Fragments are designed to implement reusable parts of UI and use them in any part of the app that is needed. They are not designed for substituting activities.
When we must use each of them?
When we have an independent screen in which there are some different UI parts (tabs, expandable screens, partial screens, etc...) we should use an activity with some fragments to implement and handle different UI parts separately in the same screen.
Each independent part of the application is actually a component that is conceptually different from other parts and it needs to have an independent activity. For example, the login part may contain some different scenarios like using username-password or using fingerprint. Each scenario can be implemented by a fragment and all login-related fragments should be handled by LoginActivity. But for example, the part of the orders in the application doesn't have a conceptual relationship with login, so it must have a different activity and of course, it may contain some fragments like OrdersFragment, SubmitNewOrderFragment, and etc that all of them must be managed by OrdersActivity.
Do not implement a UI directly in an activity. Always implement UI in fragments and add those fragments in the activity even if there is only one fragment in that activity. It helps you to have more reusable code and change UIs easier.
Never use fragments to navigate infinitely in the application even if you force the user to have a limited number of fragments in the back stack. The fact is that when you add a new fragment into the back stack and remove it, it will not be removed from the memory unless the parent activity gets destroyed and it is only not visible. So when you are using fragment manager back stack, by navigating multiple times between fragments in the same activity (especially in the case of you create a new fragment on each navigation and put them into the back stack) you will get an OutOfMemoryException in the application.
I hope it to be helpful.
This question needs to be reevaluated since Jetpack Compose has reached stable.
Jetpack Compose is Android’s recommended modern toolkit for building
native UI.
from https://developer.android.com/jetpack/compose
The typical jetpack-compose architecture is:
Single Activity, multiple composables, and glued together by jetpack navigation.
Note there's no (need for) Fragments anymore.
See Now in Android for a sample.

Why fragments, and when to use fragments instead of activities?

In Android API 11+, Google has released a new class called Fragment.
In the videos, Google suggests that whenever possible (link1, link2), we should use fragments instead of activities, but they didn't explain exactly why.
What's the purpose of fragments and some possible uses of them (other than some UI examples that can be easily be achieved by simple views/layouts)?
My question is about fragments:
What are the purposes of using a fragment?
What are the advantages and disadvantages of using fragments compared to using activities/views/layouts?
Bonus questions:
Can you give some really interesting uses for fragments? Things that Google didn't mention in their videos?
What's the best way to communicate between fragments and the activities that contain them?
What are the most important things to remember when you use fragments? Any tips and warnings from your experience?
#1 & #2 what are the purposes of using a fragment & what are the
advantages and disadvantages of using fragments compared to using
activities/views/layouts?
Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;
The ActionBar. If you want tabs up there to navigate your app, you quickly see that ActionBar.TabListener interface gives you a FragmentTransaction as an input argument to the onTabSelected method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.
The FragmentManager handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.
You can use the cool ViewPager with a FragmentPagerAdapter to create swipe interfaces. The FragmentPagerAdapter code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.
Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.
You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use ActionBarSherlock and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like the ActionBar, with tabs, overflow, split action bar, viewpager etc.
Bonus 2
The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity() with data on it. The intent is passed on to all fragments of the activity you launch.
Not sure what video(s) you are referring to, but I doubt they are saying you should use fragments instead of activities, because they are not directly interchangeable. There is actually a fairly detailed entry in the Dev Guide, consider reading it for details.
In short, fragments live inside activities, and each activity can host many fragments. Like activities, they have a specific lifecycle, unlike activities, they are not top-level application components. Advantages of fragments include code reuse and modularity (e.g., using the same list view in many activities), including the ability to build multi-pane interfaces (mostly useful on tablets). The main disadvantage is (some) added complexity. You can generally achieve the same thing with (custom) views in a non-standard and less robust way.
A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity which enable a more modular activity design. It will not be wrong if we say a fragment is a kind of subactivity.
Following are important points about a fragment:
A fragment has its own layout and its own behavior with its own lifecycle callbacks.
You can add or remove fragments in an activity while the activity is running.
You can combine multiple fragments in a single activity to build a multi-pane UI.
A fragment can be used in multiple activities.
The fragment life cycle is closely related to the lifecycle of its host activity.
When the activity is paused, all the fragments available in the acivity will also be stopped.
A fragment can implement a behavior that has no user interface component.
Fragments were added to the Android API in Android 3 (Honeycomb) with API version 11.
For more details, please visit the official site, Fragments.
Activities are the full screen components in the app with the toolbar, everything else are preferably Fragments.
One full screen parent activity with a toolbar can have multiple panes, scrollable pages, dialogs, etc. (all fragments), all of which can be accessed from the parent and communicate via the parent.
Example:
Activity A, Activity B, Activity C:
All activities need to have same code repeated, to show a basic
toolbar for example, or inherit from a parent activity (becomes
cumbersome to manage).
To move from one activity to the other, either all of them need to be in memory (overhead) or one needs to be destroyed for the other to open.
Communication between activities can be done via Intents.
vs
Activity A, Fragment 1, Fragment 2, Fragment 3:
No code repetition, all screens have toolbars etc. from that one activity.
Several ways to move from one fragment to next - view pager, multi pane etc.
Activity has most data, so minimal inter-fragment communication needed. If still necessary, can be done via interfaces easily.
Fragments do not need to be full screen, lots of flexibility in designing them.
Fragments do not need to inflate layout if views are not necessary.
Several activities can use the same fragment.
This is important information that I found on fragments:
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.
Source: https://www.pluralsight.com/blog/software-development/android-fragments
Fragments are of particular use in some cases like where we want to keep a navigation drawer in all our pages. You can inflate a frame layout with whatever fragment you want and still have access to the navigation drawer.
If you had used an activity, you would have had to keep the drawer in all activities which makes for redundant code. This is one interesting use of a fragment.
I'm new to Android and still think a fragment is helpful this way.
I know this was already discussed to death, but I'd like to add some more points:
Frags can be used to populate Menus and can handle MenuItem clicks on their own. Thus giving futher modulation options for your Activities. You can do ContextualActionBar stuff and so on without your Activity knowing about it and can basically decouple it from the basic stuff your Activity handles (Navigation/Settings/About).
A parent Frag with child Frags can give you further options to modulize your components. E.g. you can easily swap Frags around, put new Frags inside a Pager or remove them, rearrange them. All without your Activity knowing anything about it just focusing on the higher level stuff.
Fragment can be thought of as non-root components in a composite tree of ui elements while activities sit at the top in the forest of composites(ui trees).
A rule of thumb on when not to use Fragment is when as a child the fragment has a conflicting attribute, e.g., it may be immersive or may be using a different style all together or has some other architectural / logical difference and doesn't fit in the existing tree homogeneously.
A rule of thumb on when to prefer Activity over Fragment is when the task (or set of coherent task) is fully independent and reusable and does some heavy weight lifting and should not be burdened further to conform to another parent-child composite (SRP violation, second responsibility would be to conform to the composite). For e.g., a MediaCaptureActivity that captures audio, video, photos etc and allows for edits, noise removal, annotations on photos etc and so on. This activity/module may have child fragments that do more granular work and conform to a common display theme.
Fragments lives within the Activity and has:
its own lifecycle
its own layout
its own child fragments and etc.
Think of Fragments as a sub activity of the main activity it belongs to, it cannot exist of its own and it can be called/reused again and again. Hope this helps :)
A fragment lives inside an activity, while an activity lives by itself.
If you've ever written front-end before, so used front-end components like(React, Vue or Angular). Think about fragments like reusable components within an activity.
1.Purposes of using a fragment?
Ans:
Dealing with device form-factor differences.
Passing information between app screens.
User interface organization.
Advanced UI metaphors.
Why fragments?
Fragments were created to replace most of the activity use cases. And see this Android Dev Summit session.
When to use fragments instead of activities?
Always, unless you really need an API that is only available in activity.

Categories

Resources