esseara
esseara

Reputation: 880

Android - relationship between Fragment and Activity


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.

Upvotes: 3

Views: 2313

Answers (3)

Moo Gaber
Moo Gaber

Reputation: 23

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.

Upvotes: 1

Farbod Salamat-Zadeh
Farbod Salamat-Zadeh

Reputation: 20080

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.

Upvotes: 2

An SO User
An SO User

Reputation: 24998

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.

Upvotes: 1

Related Questions