Start a Project

Investigating the fragments

In this blog,
I will show some interesting and important things to use fragment efficiently.
 
A Fragment is a part 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.

Or we can say that Like a “subactivity” that you can reuse in different activities.

 

How to reuse the existing fragment

Here, I will show you how to reuse the fragment if it is already in the stack.

First, I have created simple frameLayout for adding the dynamic fragments.

FrameLayout: FrameLayout is one of the useful layout provided by the android system, which allows User Interface widgets to be overlapped with each other.

Now, I have shown some code snaps for managing fragment classes.

We have two methods for finding a particular fragment is in the frame or not.

  1. findFragmentById

  2. findFragmentByTag

 

How to use findFragmentById

For the finding the fragment is available in the frame, we use findFragmentById 

findFragmentById: Finds a fragment that was identified by the given id when inflated from XML.

Here, I have wanted to add the Fragment1.class

Then,

We check if it is already in the frame then pop it from the back stack and add again.

 

How to use findFragmentByTag

The second method for getting the fragment is findFragmentByTag.

findFragmentByTag: Finds a fragment that was identified by the given tag when inflated from XML.

For finding the fragment by tag, First, we have to set the tag to the particular fragment

Here, I have set a tag of my Fragment1 to fTag.

And then get the particular fragment by tag. And

In above code snap, I have got the fragment if not null. And simply detach and attach to the transaction.

If null then added it to the frame and assign a tag for better use.

 

 

Exit mobile version