ChatGPT解决这个技术问题 Extra ChatGPT

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?

an activity can be thought of as an independent micro-service while a fragment can be thought of as an embeddable dependency

G
Glenn Bech

#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.


first of all ,thanks.i appreciate people who give informative(yet short) answers and not just give me a link to a manual .anyway, besides extra features to work on special classes , can you think of advantages and disadvantages of working with fragments?
I think you have to be more direct in you questioning. I just gave four major advantages above.
ok , what about disadvantages compared to customized views and activities?
One fragment should never talk directly to another fragment - instead go through the parent activity. This way you don't end up with spaghetti code but easy to manage code.
Re "The best way to communicate between fragments are intents" Huh? I don't think so. intents are for communicating between activities. The way to communicate "between fragments" is .. don't. That is, don't communicate directly fragment-to-fragment, instead a fragment should do a callback in a custom interface to its owning activity, which decides what to do.
R
Robert Ramonet

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.


updated question . it now has links to the videos of google. also, thanks for the explanation, but i still need clarification about my question.
Read the dev guide entry, it has more than enough details. It's unlikely that you will get an answer to 'cool uses of fragments' on SO -- way to vague and there is no single answer. Number 4 is specificlly answered in the dev guide-- developer.android.com/guide/topics/fundamentals/…
as far as i know , this method creates a dependency of which activity can contain which fragment . also , please answer the main questions (the first two) .
Thanks to android developer for insisting on answers to the basic question. ATM I've not seen anything useful to me in the Fragment class over using the XML "include" tag. The kinds of things that I would find valuable would be the ability to specify one layout that would magically morph into the best user experience at all resolutions. From what I can tell you still need to do that in code by yourself. Another potential value would be a way to bundle code + resources into reusable components not found in the reusing apps, but again does not appear to be there. I want one really good reason.
I'm starting to understand the way Google suggest using fragments, but I fairly agree with @NikolayElenkov.. To me, using Activities still seems to be the most robust and the less complex way..
P
Peter Mortensen

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.


1. As you mentioned on #8, it doesn't have to have a layout. 6. you missed the part after "means" . Anyway, thanks for helping others make this clearer. I will give you +1 .
Regarding #8, a possible example of no-layout fragment (i.e. 'headless' fragment) would be one that carries out a task that despite being somewhat short (such as a short HTTP request) is still required to survive configuration changes and thus depends on the exact fragment instance being preserved across them (by using setRetainInstance(true) on the fragment). As for layout fragments, setRetainInstance(true) doesn't make much sense, as it prevents resources associated with their views from being freed up when necessary (i.e. a memory leak).
NOTE: "#8" is now "#7".
P
Pang

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


That's true, but there are solutions for this: use Parcelable when it's not a huge object (and there is a plugin to make it easier), and if it's a huge object, you can always use a static reference that will be set to null when you get to the new activity (or when you destroy it, depending on your requirement).
@androiddeveloper: "use Parcelable" fits my definition of a "data passing headache that is avoided by using Fragments". If there is complex shared state that needs to persist while a series of screens passes by, an Activity + Fragments is a good solution, IMHO. (Though I abandoned the Fragment back stack, and did my own managing of what "back" means.)
Using interface design pattern between fragments through a container activity is a much modular approach to pass not just objects but also click event listeners and method arguments back to other fragments or to the main container activity.
P
Pang

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.


perfect answer!
P
Peter Mortensen

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.


Yes. However, I'm still sometimes confused about the correct way to use fragments, and that's because of the complex lifecycle of both fragments and activities.
@androiddeveloper do you just use activities mostly?
@MichaelAlanHuff When supporting tablets, I think it's better to use Fragments. Also, when supporting orientation changes and other similar events, you might want to use DialogFragment, as it allows you to restore them
@androiddeveloper, that's what I think as well. I haven't used DialogFragments as often. For helping modularity of logic, a lot of android developers are starting to use custom views to hold the logic a la square's mortar. Here is a recent talk on custom views given by an engineer from Airbnb vimeo.com/127799187
@MichaelAlanHuff using fragments could be also useful if you think the current screen could be a part of another screen.
e
einschnaehkeee

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.


m
maniix

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 :)


Actually, about the second point ("its own layout"), this is optional . A fragment doesn't have to have a view at all.
D
Darren Finch

A fragment lives inside an activity, while an activity lives by itself.


"on itself"? Perhaps "on its own"? Or "by itself"?
A
Abhinav Atul

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.


D
Damola Obaleke

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.


P
Prithiv Dharmaraj

1.Purposes of using a fragment?

Ans: Dealing with device form-factor differences. Passing information between app screens. User interface organization. Advanced UI metaphors.

Dealing with device form-factor differences.

Passing information between app screens.

User interface organization.

Advanced UI metaphors.