A fragment represents a modular portion of the user interface within an activity. A fragment has its own lifecycle, receives its own input events, and you can add or remove fragments while the containing activity is running.
Fragment are part of an activity.
It is Similar to an activity but not an Activity .
A Activity may contains multiple fragments .
Fragment has its own lifecycle like activity
Fragment LifeCycle Compare to Activity LifeCycle
Create An Fragment
Right click on layout folder or project named folder in android studio.
select Fragment.
Select Blank Fragment OR Fragment According to your need.
Use Fragment
Fragment need to Instantiate OR Initialized Inside an Activity And Need to place in side some Container View Like ( FrameLayout , etc…)
Method To create/Invoke Fragment
1. Using Fragment Manager
Old Style
val homeFragment = HomeFragment()
val ft : FragmentTransaction = supportFragmentManager.beginTransaction()
// add new fragment to layout container
// add to back Stack
ft.add(R.id.framelayout , homeFragment)
// OR
// replace prev fragment with new fragment
// does not add to back stack
ft.replace(R.id.framelayout , homeFragment)
// commit the chnages
ft.commit()
We Need FragmentManager for Fragment it can be get by supportFragmentManager
than we need FragmentTransaction object to perform transaction it can get by beginTransaction() method of supportFragmentManager
FragmentTransaction object contains multiple methods to perform transactions of fragments and last we need to perform commit() method of it to complete the transaction .
Inside Activity from where you want to change fragment Create NavController object
The navigation controller is one of the key concepts in navigation. It holds the navigation graph and exposes methods that allow your app to move between the destinations in the graph.
private lateinit var navController: NavController
// To Initialize inside activity
// ... Inside onCreate Method
navController = Navigation.findNavController(this@MainActivity,R.id.nav_host_fragment)
// OR
// To Initialize inside fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navControtter = Navigation.findNavControtter(view)
}
Now to We can Navigation between fragment for that perform this code on some button or condition