Fragments
What is Fragment?
A Fragment represents a modular and reusable portion of your app's UI.
Fragment has its own layout , Lifecycle and manages its own input events
Fragment cant live on their own they must be hosted by activity or fragment and its view hierarchy becomes the past of its host’s view hierarchy
How is Fragment Modular and Reusable?
Fragment is Modular because the UI can be divided into chunks and Dividing your UI into fragments makes it easier to modify your activity's appearance at runtime. While your activity is in the STARTED lifecycle state or higher, fragments can be added, replaced, or removed
Fragment is reusable because you can use multiple instances of the same fragment class within the same activity, in multiple activities, or even as a child of another fragment.
How can fragments be used?
Fragments can be used with directly Activity or other Fragments, You can define a Fragment tag in xml of host and inflate it statically or dynamically.Fragment is also used with BottomNavigationView and Viewpager. You can also use it in Drawerlayout.
How can we Add a fragment in Activity?
Fragment can be added to activity in two ways:
- By adding fragment in XML file directly
- By defining Fragment tag in XML Layout file and adding Fragment dynamically
How to add a fragment using XML?
To add a fragment using XML layout, Use an <fragment> or <FragmentContainerView> tag in the XML file and mention your Fragment class name in android:name or android:class element.
How to add a fragment programmatically?
To add a fragment programmatically , Use an <FrameLayout> or <FragmentContainerView> tag in an XML file, Then use FragmentManager Class to perform FragmentTransaction.
Why is it preferred to use <FragmentContainerView> instead of <Fragment> and <FrameLayout>?
It is preferred to use <FragmentContainerView> because it provides fixes related to fragments that <FrameLayout> and <Fragment> is missing.
<Fragment> tag is used when you want to add a fragment statically using XML But you can not use fragmentmanager to perform any transaction on It.Fragment can not be changed.
<FrameLayout> tag is used when you want to add fragment dynamically and fragment transactions can be done.
<FragmentContainerView> can be used in replacement of the both above. We can use fragment instead of fragment and it will allow us to perform transactions even if added using XML. It also eliminates the drawbacks related to animation in FrameLayout.
(Ref: Android: when / why should I use FrameLayout instead of Fragment? - Stack Overflow)
Why should we check for savedInstance before adding a fragment in Activity?
When we add a fragment in onCreate() method of activity check for savedInstanceState is null or not. And only add if it is null. Because while recreating activity the fragment does not need to be added a second time, as the fragment is automatically restored from the savedInstanceState.
How to pass an argument to a fragment while adding it?
We can pass a bundle object to an add() method while adding it and it can be retrieved using requireArguments() function in fragment class. We have used the class<Fragment> argument and Bundle in the add() method.
What is fragment Manager?
Fragment manager is a class responsible for performing actions on your fragment such as Add, Remove or replace them, And adding them to backstack.
How to access FragmentManager?
To access FagmentManager in Activity:
getSupportFragmentManager()
To access FragmentManager in Fragment:
To manage childs: getChildFragmentManager()
To get Host’s Fragmentmanager: getParentFragmentManager()
What is FragmentTransaction?
Fragment manager can perform back stack operations like Adding, Removing and Replacing based on user's interaction. Each set is committed as a single unit called FragmentTransaction.
You can group multiple actions into a single transaction—for example, a transaction can add or replace multiple fragments.
How can we perform transaction of fragment?
You can get an instance of FragmentTransaction from the FragmentManager by calling beginTransaction()
The final call on each FragmentTransaction must commit the transaction. The commit() call signals to the FragmentManager that all operations have been added to the transaction.
What are the operations that can be performed on Fragment?
add(), remove and replace() transactions can be performed on Fragments using Fragment manager and FragmentTransaction.
What is an add() transaction?
add() is used to add a fragment in the same root.
What is the remove() transaction?
remove() is used to fragment from the host.
What is replace() transaction?
Replace is used to replace an current fragment in a container with a new Instance of fragment you provide. It is equivalent to removing existing and adding a new fragment.
Why is it recommended to setReorderingAllowed(true) should be set to true?
When this flag is enabled it ensures that if multiple transactions are executed together, then any intermediate fragment does not go through lifeCycle or animation or transition phase.
What is addTobackStack() ?
If you have added or replaced many Fragments on a Fragment container. There is no way to go back to the previous Fragment on a Back Button Pressed.This transactions can be stored in the back stack using addToBackStack() call.
addToBackStack() = save reverse of the action
If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.
If you don’t call this method transactions are not saved and fragments are destroyed after the transaction is finished so you can not get back to that fragment.
(Ref: Fragment addToBackStack- Stack Overflow)
What is the meaning of addToBackStack with null parameter? - Stack Overflow)
What is the difference between commit() and commitNow()?
commit() is asynchronous, It does not perform transactions immediately, It schedules transactions on the UI main thread to perform as soon as possible.
commotNow() is synchronous, It performs transactions immediately on the UI main thread.But it is not compatible with addToBackStack().
What is executePendingTransactions() used for?
This method is called when you want to perform all transaction immediately scheduled by commit()
How to show and hide the fragment without affecting the Lifecycle of fragment?
Use the FragmentTransaction methods show() and hide() to show and hide the view of fragments that have been added to a container. These methods set the visibility of the fragment's views without affecting the lifecycle of the fragment.
How is FragmentManager used to get Fragment?
You can get existing fragment using two ways:
- Using Container ID: To get the current fragment assigned in the container by passing an id to the given method.
findFragmentById()
- Using tag: To get any fragment that is added or replaced can be obtained using
findFragmentByTag()method by passing a tag declared in xml or while transaction.
What is popBackStack() used for?
It is the method of FragmentManager used to pop the back stack. You can also pass a transaction key that is used while adding a transaction in backstack.
Why should Fragment be preferred over activity?
Fragment provide modularity and reusability of UI
Fragment can be used with viewPager so it can be used in BottomNavigationView and Tabbed Layout
How would you communicate between two Fragments?
The communication between fragments should not be done directly. There are three ways of doing so.
- With the help of ViewModel
- With the help of Interface
- using the Fragment Result API
What is and How to use the Fragment Result API?
When you want to share one time data between two fragments or between fragment and its host It can be done using the Fragment Result API which is introduced in Fragment version 1.3.0.
It’s lifecycle-safe — when receiving a result, you can work with the fragment view
For that the fragment which sends data should set Fragment Result and the fragment or host which wants to receive data should set Fragment Result Listener.Bundle is the object that is set and retrieved with the key.
The thing that must need to be taken care of here is to choose the FragmentManager.when:
- Between two fragments: Use Parent Fragment Manager in both the fragment
- Between Host and child Fragment: Use parent Fragment Manager in child and use Child fragment manager in Host
(Ref:Fragment Result API | Medium )
Explain Fragment Lifecycle?
onAttach()
onCreate()
onCreateView()
onViewCreated()
onViewStateRestored()
onStart()
onResume()
onPause()
onStop()
onSaveInstanceState()
onDestroyView()
onDestroy()
onDetach()
How to use a Fragment with ViewPager?
Viewpager is a layout Manager that can be added in any Layout File.It is mostly used with Fragments and FragmentPagerAdapter or FragmentStatepagerAdapter.
- Create Fragments that you need.
- Create an adapter that extends either FragmentPagerAdapter or FragmentStatePagerAdapter
- It overrides: getCount(), getItem(), getPageTitle() methods.
- getItem method returns the fragment that needs to be shown on current position
- Add a ViewPager in Layout XML
- In the Host that contain ViewPager(Activity or Fragment)
- Get a viewPager by ID
- Create an Adapter and initialize it
- Set Adapter in ViewPager
ViewPagercan also be used with the conjunction of Tab layout and Bottom navigation View.
(Ref:https://developer.android.com/develop/ui/views/animations/screen-slide)
What is the difference between FragmentPagerAdapter vs FragmentStatePagerAdapter?
FragmentPagerAdapter stores each fragment visited by the user in Memory.Only view is destroyed while out of focus,So when Fragment is revisited only view needs to be recreated.
FragmentStatePagerAdapter does not save the fragment in memory , It is destroyed when not visible to the user. It is useful to enhance performance when there are too many fragments.You have to recreate the Fragment each time.
How to use a ViewPager withTabbedLayout?
- Create the viewPager as mentioned above.
- Add TabLayout in XML Layout File.
- Get TabLayout using ID
- Set Up tabLayout with ViewPager using TabLayout.setupWithViewPager(viewPager)
(Ref:https://www.geeksforgeeks.org/viewpager-using-fragments-in-android-with-example/)
How to use a fragment with BottomNavigationView?
Bottom navigation bars make it easy for users to explore and switch between top-level views in a single tap. They should be used when an application has three to five top-level destinations.
We can directly use fragments with BottomNavigationView by Performing fragment Transactions.To Do So we need to perform following steps:
- Create a Menu XML resource File
- Add a frame Layout in XML
- Add a
BottomNavigationViewIn Layout XML and add created XML menu file with menu tag - Get BottomNavigationView Object using Find by ID
- Set onNavigationItemSelectedListener for BottomNavigationView
- Based on the selected Item in Navigation choose the fragment and perform fragment transaction (Replace) in the Frame Layout Container
(Ref:https://www.geeksforgeeks.org/bottomnavigationview-inandroid/)
How to use a ViewPager with BottomNavigationView?
We can use Fragment using ViewPager and BottomNavigationView as follow:
- Create a Menu XML resource File
- Add a
BottomNavigationViewIn Layout XML and add created XML menu file with menu tag - Create and setup ViewPager as above
- Get BottomNavigationView Object using Find by ID
- Set onNavigationItemSelectedListener for BottomNavigationView
- Based on the selected Item in Navigation setCurrentItem in Viewpager
- Set OnPageChangeListener and override onPageSelected() in this and check the menu option
(Ref:https://droidmentor.com/bottomnavigationview-with-viewpager-android/)
Why is it recommended to use only the default constructor to create a Fragment?
Whenever Fragment is recreated after configuration change, OS calls the no-argument constructor of the fragment because it has no idea with what argument we have created a fragment so it is preferred to use only the default constructor.