In Android, the fragment is part of the activity. The fragment is a portion of the user interface on the screen.it is a modular Android activity that is used to create UI. The fragment is inside of activity. It is dependent on the host activity on the application. The UI is flexible on all devices.
Let’s take one example of the Android Fragment
Methods of the Android Fragment.
- OnAttach(): This is the very first method in the life cycle of fragments.
- OnCreate(): when loading a fragment this method is called first and loads UI on the application.
- OnCreateVIew(): The system calls this method to create the user interface of the fragment. This root fragment layout returned as the view.
- OnViewCreated(): This method flows the hierarchy of fragments and also has been created by the fragment.
- OnStart (): This method to make the fragment.
- OnResume(): This method is called to make the visible fragment.
- OnPause(): This method is called when the back press or app is killed.
- OnStop(): This method is called when the back press or app is killed.
- OnDestroyView (): This method is used to clean up all kinds of resources as well as view hierarchy.
- OnDestroy(): It is called to perform the final cleanup of the fragment’s state.
- OnDetach (): This method executes the disassociate of the fragment from the host activity.
Example of LIfecycle
Step 1: Create an activity_main.xml in the layout folder.
Step 2: Create an activity_main.kt or java in your project.
Step 3: Create a first_fragment.xml in your project.
Step 4: Create a FirstFragment.kt or java in your project.
Step 5: Create a second_fragment.xml in your mobile app development project.
Step 6: Create a SecondFragment.kt or java in your project.
Step 7: Create a navgraph.xml in the layout folder.
Step 8: Image of navigraph.
Happy coding!