In this tutorial you will learn about the Android Fragments and its application with practical example.
Fragment is a part of Activity or also we can say sub activity. It represent multiple screen inside an activity.
The fragment’s lifecycle is affected by the host activity’s lifecycle, For example if host activity is in pause status so all fragment will be in pause status and if activity is destroyed so all fragment will be destroyed.
For creating an Fragment you need to extend through Fragment class or in other words you need to create subclass of Fragment. As I told you before that fragment is a part of activity or sub activity so Fragment class has code that looks like an Activity. It contains callback methods like an activity, like onCreate(), onStart(), onPause() and onStop(). You can understand lifecycle of Fragment from below Image.
- onAttach() : It calls when Fragment attach with an Activity, onAttach() method is called only once.
- onCreate() : It calls when creating Fragment. It is used to initialize essential components of fragment.
3.onCreateView() : It is called by the system for drawing User Interface for Fragment. For drawing UI for fragment , you need to return a View that is the root of fragment’s layout.
- onActivityCreated() : It is called after onCreateView() method when the host activity is created.
5.onStart() : It makes fragment visible.
- onResume() : It makes fragment active.
7.onPause() : The system calls this method when fragment is no longer active. First indication of this method is that user is leaving the fragment it does not mean that fragment is being destroyed.
8.onStop() : It is called when the fragment is no longer visible.
9.onDestroyView() : this method allows the fragment to clean up resources.
10.onDestroy() : this method allows the fragment to do final clean up of fragment state.
- onDetach() : It is called when the fragment is no longer associate with host activity.
Types of Fragment : Single Frame Fragment , List Fragment, Fragment Transaction.
In below code you will get information about Fragment creation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.example.myapplication; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FragmentTest extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_layout, container, false); return view; } } |