Fragment Tricks

  There’s a lot of information out on the web as people have used the API gotten kind of familiar with it and in some ways kind of got bitten by it.There’s a lot of complexity there.

Why use fragment at all?

If we want to group UI components, couldn’t we just create a ViewGroup or maybe a re-usable XML layout definition? Yes but the real power in fragments goes beyond grouping UI elements.They allow us to fully modularize our activity, including the lifecycle events they receive in the app state that they maintain.Treat each fragment as though it were a mini activity.

Breaking your app into different activities. Having a single monolithic activity increases the complexity of your code.

Making the creation and management of intent filters much harder and making it more difficult to maintain, test, and read your activity code. It also increases the risk of tightly coupling independent components and makes it much more likely to introduce security risks if the single activity includes both sensitive information and information that’s safe to share.

When to use Activity?

A good rule of thumb is to create a new activity whenever the context changes.For example, displaying a different kind of data while switching from viewing to entering data.

Single Activity Architecture

With a single activity architecture, you simply have one activity and you have your view for your screen number A at number A. and instead of having a new activity for your screen B, you simply swap the view.

Fragment lifecycle 

The basic lifecycle events are much the same as the parent activity.It moves through the cycle of starts, resumes, pauses and stops those same lifecycle events will be triggered within the fragment itself.In most cases, you can simply move anything that you would have put into the activity lifecycle handles into the corresponding fragment handlers.

Fragment Lifecycel


onCreateView : Fragment introduced a new event specifically for UI.Here, You construct or inflate your UI, hook up to any data sources, and return it you the parent activity which can then integrate it into its view hierarchy.

There’s a correspond onDestroyView handler, which is called immediately before the fragment is added to the back stack, independent of the parent activity, onDestroyView is where you should clean up any resources specifically related to the UI, such as bitmaps in memory, cursors to data, anything like that to help ensure that your app’s memory footprint isn’t bloated by data that’s not needed  when the fragment isn’t visible.

Now as soon as the fragment is returned from the back stack,onCreateView is call and you can re-create the UI and reconnect data sources before your fragment transitions through the rest of the lifecycle to become active again.And because a fragment can only exist within an activity.

We also need callbacks to tell us when a fragment is attached and detached from its parent.OnAttach is your opportunity to get a reference to the parent activity.While onDetach is the last thing that happens,

onActivityCreated This notifies our fragment that the parent activity has completed it’s onCreate handler

Fragment Tricks

I am going to be writing about a few effective patterns for using the fragment API in your apps.Some of these are going to be they may seem a little bit basic, but they’re also things that are going to help you build apps in a way that factors your code effectively, encapsulates things and, makes sure that you can keep your code clean.

Where is fragment API came from?

As Android started moving into large screen devices in honeycomb, It is realizing that there are a few specific patterns in the way that some apps are put together, especially apps of the time.You’ve got one area that’s devoted to your navigation, and you got another area that’s devoted to content.When you put these two things together, you can imagine on a small screen device you might see the navigation as on screen that advances to the content screen, and when you’re on a larger screen device you’re able to show the same thing side by side.

It was something that you could use to factor out your activity components into two separate pieces that you could show differently based on different device configurations.Now this works really well for some application like Gmail, but your app probably isn’t Gmail.If you followed the development of app design.This sort of pattern just doesn’t fit for a lot of things.

However, it’s still extremely useful for representing your application as a series of destinations.So even on a small screen device, you might have an app that looks something like this.

Fragment Transition animation

Download this project from GitHub.

We’ve got our little application that–where you can order some flowers.For each one of these screens, you can perform a replace transaction to replace the destination that you were looking at previously with the new one.Replace transaction will remove any fragment in the container and then add new fragment. So the nice thing about is that you can place these particular transaction on the back stack, and we’ll go ahead and handle that back navigation for you

Now the nice thing about this is that the content and navigation pane separation isn’t limited to just large screens. This can really help to keep your chrome stable.

In your application you have things like bars,net drawers,bottom navigation bars, any of these things that you want to keep stable and perform some consistent animations from one screen to another this really lets you do it in a way that is really difficult to accomplish with the activity  to activity transitions where you can’t preserve that kind of continuity in your UI as you navigate deeper in your app’s hierarchy.

Navigation Flows

I’m talking about those step-by-step flows that you have in your application.So when you have a checkout or a sign up or a setup wizard, the users are going to go step by step through their navigation, and then they might want to wander back using the back button and then go forward again and then when they’re all done, you want to be all done with that.You don’t want that one user to be able to go back through the checkout process again

Key to back stack management

1.Do maintain the back stack as you navigation forward(It’s so much easier to manage your back stack if you choose the direction your user is going to go on the back stack as you navigation forward).

2.Don’t , at the time the user press the back button, choose what they’re going to do.That’s a lot harder to manage. So to take advantage of this kind of thing, sometimes you need to do some synthetic back stack management that means if you have an external link into your application, some kind of deep, nested thing, they’re selecting a particular cart item.When they hit the back button, you don’t want them to go to some–the main screen, you want them to go into the category, perhaps DON’T decide on back button navigation behavior just-in-time.

Repeated commits start and stop each fragment.

If you make repeated transactions, then that means that each one of that transaction you’re going to start and stop those fragments as you execute each one in turn.So that can be really expensive right?

how do you can go ahead and maintain that back stack state?

While still not doing a whole lot of really heavyweight work as you start and stop each one of those fragments along the way? Because you have to create all those views, tear them down again, inflation.It seems like a lot of unnecessary work.

setReorderingAllowed(true) :It allows all of the execution to happen all at once without changing your fragment state. And then at the very end, we bring up all the fragments that need to be brought up and tear down all the fragments that need be torn down.and now you’re fragments don’t have to go through all that.


ViewGroup or Fragment?

Using a custom ViewGroup or a Fragment in these case, Is does it implement mechanism or does it implement policy? Is it an isolated widget that generates its own input events?(Is it an isolated widget, or does it connect app logic?)

Views should really only be responsible for displaying information and publishing direct user interaction events.These end up being very low level events, like button was clicked user scrolled something.

These are responsible for drawing text and these other sorts of operations that are user interaction, wheres fragments integrate with the surrounding lifecycle and they may be aware of the app components.

Fragment is really what gives context to everything  that you’re doing in your UI.(Bind to a service, communicate with your app’s data model performing a database query, so on and so forth)

So you should never use a Fragment when a View will do, but you also want make sure that you’re not adding outside dependencies to your Views. It’s definitely a code smell if you ever find yourself doing something like trying

To bind a service from a view implementation, or trying to make a network call or again, trying to integrate with anything that’s outside of the realm of just that one individual view.

But that means that there’s a whole.It means that you can’t building just something that simple as completely self-contained like button

Don’t use a Fragment when just a composite custom ViewGroup, or even just a layout resource that you can use an include tag, wild the job better.


Related Post

Lifecycle Aware Components

Room Persistence Library



ConstraintLayout 1.1.x


Leave a Reply

Your email address will not be published. Required fields are marked *