Using tabs inside a Fragment (not FragmentActivity) - android

I'm currently creating an app in which the main screen is build up out of 2 Fragments.
When the user selects options on the main screen, one part of the screen gets replaced by a new Fragment, all pretty much basic stuff.
Now I'm trying to create a screen with several tabs, which all open a new fragment inside them. I had this working with regular intents, but that was before switching to Fragments.
I read that this is possible by using a FragmentActivity, but sadly you can't replace a Fragment with a FragmentActivity, simply because the transaction won't let you.
Is there any way of doing this inside an ordinary Fragment? Or should I try mimicking the behavior by using a layout with a fragment inside which gets replaced by another one at the press of a button, much like the main screen? (Or won't that work due to fragments in fragments?)

There is an example in Android's support library that describes what seems to be what you need. You can find it here: FragmentTabs.

Related

Android Studio- starts with 2 fragments

I searched through the site but could not find an answer so here is my question.
I am using Android Studio 3.6 and when I start a new project and choose Basic Activity there are two fragments appearing in layout. So in layout there are .xml files activity_main,content_main,fragment_first and fragment_second. Therefore, when I start a new project, I get a different screen than the usual "hello world" screen. To add, I cannot basically edit the fragments. So, how can I back to "normal" and start without these fragments?
When you create a basic activity, you basically create an activity with two fragments. this means that basic activity by default provides two fragments that you can edit and use. basically, it's almost the same with bottom navigation activity. the difference is only in basic activity there is no bottom navigation.
if you want to make one activity app. you don't really need to use fragments. so you can just make a Empty activity instead of basic activity. if you want to make your activity fragmented in the future, you can add it later.

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.

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

How to add contents into FragmentTabsPager when the content is defined as Activity?

I am using The FragmentTabsPager, but not sure how to assign the contents of one of the tabs when the content itself is a complicated Activity that embeds ListViews, and a host of other activities. This is only for small one pane screen, so can I attach this Activity inside one of the tabs without changing the whole thing into a Fragment class? Is it right to simply change : onCreate to on onCreateView (inflate) and this becomes getActivity()?
EDIT: http://www.themobilemontage.com/
Download in the link above
Tutorial 9: Integrating Web Services Into Your Android App
http://www.youtube.com/watch?feature=player_embedded&v=QTO5a1IeBl8
The Main class is edu.gvsu.cis.toptracks.TopTrackListActivity which extends from Activity, so not sure how to convert this class (into a Fragment or FragmentActivity?) and place it as one of the tab contents if I start a new Blank Activity from template Blank Activity -> Navigation Type -> Fixed Tabs + Swipe.
Any suggestions as I tried to change the TopListActivity but not really clear what to do?
if I could convert this
There is no FragmentTabsPager in Android. You cannot embed an activity into a FragmentTabHost, which is what I assume you mean. You can convert your activities to fragments, then use those with FragmentTabHost or any of the other modern tab solutions for Android.
This is only for small one pane screen, so can I attach this Activity inside one of the tabs without changing the whole thing into a Fragment class?
No. Activities-in-tabs has been deprecated for well over two years.

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