{"id":2118,"date":"2016-12-02T07:44:07","date_gmt":"2016-12-02T07:44:07","guid":{"rendered":"http:\/\/abhiandroid.com\/ui\/?p=2118"},"modified":"2019-06-12T12:18:16","modified_gmt":"2019-06-12T12:18:16","slug":"fragment-lifecycle-example-android-studio","status":"publish","type":"post","link":"https:\/\/abhiandroid.com\/ui\/fragment-lifecycle-example-android-studio.html","title":{"rendered":"Fragment Lifecycle Tutorial With Example In Android Studio"},"content":{"rendered":"<p>In Android, Fragment is a part of an activity which enable more modular activity design. It will not be wrong if we say a fragment is a kind of sub-activity. It represents a behavior or a portion of user interface in an Activity. We can combine multiple Fragments in single Activity to build a multi pane UI and reuse a Fragment in multiple Activities. A fragment must always be embedded in an activity and the fragment&#8217;s life-cycle is directly affected by the host activity&#8217;s life-cycle.<\/p>\n<p>Recommended\u00a0read? <a href=\"\/programming\/activity-life-cycle\">Activity Life Cycle In Android<\/a><\/p>\n<hr \/>\n<h4><strong>Fragment Lifecycle\u00a0<\/strong><strong>In Android:<\/strong><\/h4>\n<p>In Android, Fragments have their own life cycle very similar to an Activity but it has extra events that are particular to the Fragment\u2019s view hierarchy, state and attachment to its activity.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-2248\" src=\"\/ui\/wp-content\/uploads\/2016\/11\/Fragment-Life-Cycle-In-Android.jpg\" alt=\"Fragment Life In Android\" width=\"806\" height=\"491\" srcset=\"https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/11\/Fragment-Life-Cycle-In-Android.jpg 806w, https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/11\/Fragment-Life-Cycle-In-Android-300x183.jpg 300w, https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/11\/Fragment-Life-Cycle-In-Android-768x468.jpg 768w\" sizes=\"auto, (max-width: 806px) 100vw, 806px\" \/><\/p>\n<p>Here is the list of methods which you can to override in your Fragment class \u2212<\/p>\n<p><span style=\"color: #008000;\"><strong>1.\u00a0 onAttach():<\/strong><\/span> The fragment instance is associated with an activity instance.This method is called first, even before onCreate() method. This method let us know that our Fragment has been attached to an activity.<\/p>\n<p>Below is the example code of onAttach() method.<\/p>\n<pre>@Override\r\npublic void onAttach(Activity activity) {\r\nsuper.onAttach(activity);\r\n\/\/ add your code here which executes when fragment instance is associated\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>2. onCreate():<\/strong><\/span> This will be called when creating the fragment. It means when a new fragment instance initializes, which always happens after it attaches to the host.<\/p>\n<p>Below is the example code of onCreate() method.<\/p>\n<pre>@Override\r\npublic void onCreate(Bundle savedInstanceState) {\r\nsuper.onCreate(savedInstanceState);\r\n\/\/ add your code here which executes when fragment's instance initializes\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>3. onCreateView():<\/strong><\/span> The will be called when it&#8217;s time for the fragment to draw its UI(user interface) for the first time. To draw a UI for our fragment we must return a View component from this method that is the root of our fragment&#8217;s layout. We can also return null if the fragment does not provide a UI.<\/p>\n<p>Below is the example code of onCreateView() method.<\/p>\n<pre>@Override\r\npublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\r\n\r\nView v = inflater.inflate(R.layout.fragment_test, container, false);\r\n\/\/ add your code here to draw the UI for the first time means in this method we can get the reference of the views which are created \u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\/\/ in our xml file\r\n\r\nreturn v;\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>4. onViewCreated():<\/strong><\/span> This will be called after onCreateView() method. This method is particularly useful when inheriting the onCreateView() method implementation but we need to configure the resulting views such as with a ListFragment and when to set up an adapter.<\/p>\n<p>Below is the example code of onViewCreated() method.<\/p>\n<pre>@Override\r\npublic void onViewCreated(View view, Bundle savedInstanceState) {\r\nsuper.onViewCreated(view, savedInstanceState);\r\n\/\/ add your code here which executes after the execution of onCreateView() method.\r\n\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>5. onActivityCreated():<\/strong><\/span> This method is called after the onCreateView() method when the host activity is created. This method indicates that the activity\u2019s onCreate() has completed.<\/p>\n<p>Below is the example code of onActivityCreated() method.<\/p>\n<pre>@Override\r\npublic void onActivityCreated(Bundle savedInstanceState) {\r\nsuper.onActivityCreated(savedInstanceState);\r\n\/\/ add your code here which executes when the host activity is created.\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>6. onStart():<\/strong><\/span> This method is called once the fragment gets visible.<\/p>\n<p>Below is the example code of onStart() method.<\/p>\n<pre>@Override\r\npublic void onStart() {\r\nsuper.onStart();\r\n\/\/ add your code here which executes when the Fragment gets visible.\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>7. onResume():<\/strong> <\/span>This method is called when the Fragment is visible and intractable.<\/p>\n<p>Below is the example code of onResume() method.<\/p>\n<pre>@Override\r\npublic void onResume() {\r\nsuper.onResume();\r\n\/\/ add your code here which executes when the Fragment is visible and intractable.\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>8. onPause():<\/strong> <\/span>This method is the first indication that the user is leaving the current fragment or fragment is no longer interactable. It occurs when any Fragment Transition processed or Fragment is removed.<\/p>\n<p>Below is the example code of onPause() method.<\/p>\n<pre>@Override\r\npublic void onPause() {\r\nsuper.onPause();\r\n\/\/ add your code here which executes when user leaving the current fragment or fragment is no longer intractable.\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>9. onStop():<\/strong><\/span> This method is called after onPause() method.Fragment going to be stopped by calling onStop(). This method calls when the Fragment is no longer visible. it occurs either after the fragment is about to be removed or Fragment Transition is processed(replace Fragment) or when the host activity stops.<\/p>\n<p>Below is the example code of onStop() method.<\/p>\n<pre>@Override\r\npublic void onStop() {\r\nsuper.onStop();\r\n\/\/ add your code here which executes Fragment going to be stopped.\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>10. onDestroyView():<\/strong> <\/span>This method is called when the view and other related resources created in onCreateView() method is removed from the activity\u2019s view hierarchy and destroyed.<\/p>\n<p>Below is the example code of onDestroyView() method.<\/p>\n<pre>@Override\r\npublic void onDestroyView() {\r\nsuper.onDestroyView();\r\n\/\/ add your code here which executes when the view's and other related resources created in onCreateView() method are removed\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>11. onDestroy():<\/strong> <\/span>This method is called to do final clean up of the Fragment&#8217;s state but Not guaranteed to be called by the Android platform. This method called after onDestroyView() method.<\/p>\n<p>Below is the example code of onDestroy() method.<\/p>\n<pre>@Override\r\npublic void onDestroy() {\r\nsuper.onDestroy();\r\n\/\/ add your code here which executes when the final clean up for the Fragment's state is needed.\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>12. onDetach():<\/strong><\/span> This method called after onDestroy() method to notify that the fragment has been disassociated from its hosting activity means Fragment is detached from its host Activity.<\/p>\n<p>Below is the example code of onDetach() method.<\/p>\n<pre>@Override\r\npublic void onDetach() {\r\nsuper.onDetach();\r\n\/\/ add your code here which executes when fragment has been disassociated from its hosting activity\r\n}\r\n<\/pre>\n<hr \/>\n<h4><strong>Fragment Lifecycle\u00a0Example In Android Studio:<\/strong><\/h4>\n<p>Below is the example of Fragment Life Cycle. In this example we show the use of Different callback methods of Fragment. In this we create a Activity and define a Fragment in Activity using &lt;fragment&gt; tag. In our Fragment i.e TestFragment we override all the methods and in each method we set a message that displays in our Log file.<\/p>\n<p>Below you can download code, see final output and step by step explanation of the example:<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"https:\/\/github.com\/abhisheksaini4\/FragmentLifeCycle\" target=\"_blank\" rel=\"nofollow\">Download Code<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-2250\" src=\"\/ui\/wp-content\/uploads\/2016\/12\/Fragment-Life-Cycle-Example-In-Android-Studio.jpg\" alt=\"Fragment Life Cycle Tutorial With Example In Android Studio\" width=\"792\" height=\"361\" srcset=\"https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/12\/Fragment-Life-Cycle-Example-In-Android-Studio.jpg 792w, https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/12\/Fragment-Life-Cycle-Example-In-Android-Studio-300x137.jpg 300w, https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/12\/Fragment-Life-Cycle-Example-In-Android-Studio-768x350.jpg 768w\" sizes=\"auto, (max-width: 792px) 100vw, 792px\" \/><\/p>\n<p><span style=\"color: #008000;\"><strong>Step 1:<\/strong> <\/span>Create a new project and name it IncludeTagExample<\/p>\n<p><span style=\"color: #008000;\"><strong>Step 2:<\/strong> <\/span>Open res -&gt; layout -&gt;activity_main.xml (or) main.xml and add following code:<\/p>\n<p>In this step we open xml file and then create a fragment to display the Fragment in our Activity.<\/p>\n<pre>&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\nxmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"match_parent\"\r\nandroid:paddingBottom=\"@dimen\/activity_vertical_margin\"\r\nandroid:paddingLeft=\"@dimen\/activity_horizontal_margin\"\r\nandroid:paddingRight=\"@dimen\/activity_horizontal_margin\"\r\nandroid:paddingTop=\"@dimen\/activity_vertical_margin\"\r\ntools:context=\".MainActivity\"&gt;\r\n&lt;!-- Take a fragment in our activity --&gt;\r\n&lt;fragment\r\nandroid:id=\"@+id\/test_fragment\"\r\nclass=\"com.fragmentlifecycle.TestFragment\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"match_parent\"\r\ntools:layout=\"@layout\/fragment_test\" \/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 3:<\/strong><\/span> Open\u00a0\u00a0 src -&gt; package -&gt; MainActivity.java<\/p>\n<p>In this step we don&#8217;t add anything because we already add a Fragment from our xml file.<\/p>\n<pre>package com.fragmentlifecycle;\r\n\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.os.Bundle;\r\n\r\npublic class MainActivity extends AppCompatActivity {\r\n\r\n@Override\r\nprotected void onCreate(Bundle savedInstanceState) {\r\nsuper.onCreate(savedInstanceState);\r\nsetContentView(R.layout.activity_main);\r\n}\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 4:<\/strong><\/span> Now we need a Fragment and a xml layout(xml) file. So create a new Fragment by right click on your package folder and create class and name it TestFragment and add the following code in it.<\/p>\n<pre>package com.fragmentlifecycle;\r\n\r\nimport android.annotation.TargetApi;\r\nimport android.app.Activity;\r\nimport android.app.Fragment;\r\nimport android.os.Build;\r\nimport android.os.Bundle;\r\nimport android.util.Log;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\n\r\n@TargetApi(Build.VERSION_CODES.KITKAT)\r\npublic class TestFragment extends Fragment {\r\n\r\nprivate void printLog(String s) {\r\n\/\/ display a message in Log File\r\nLog.d(\"LifeCycle:\", s);\r\n}\r\n\r\n@Override\r\npublic void onActivityCreated(Bundle savedInstanceState) {\r\nsuper.onActivityCreated(savedInstanceState);\r\nprintLog(\"onActivityCreated Called\");\r\n}\r\n\r\n@Override\r\npublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\r\n\r\nView v = inflater.inflate(R.layout.fragment_test, container, false);\r\nprintLog(\"onCreateView Called\");\r\n\r\nreturn v;\r\n}\r\n\r\n@Override\r\npublic void onViewCreated(View view, Bundle savedInstanceState) {\r\nsuper.onViewCreated(view, savedInstanceState);\r\nprintLog(\"onViewCreated Called\");\r\n\r\n}\r\n\r\n@Override\r\npublic void onAttach(Activity activity) {\r\nsuper.onAttach(activity);\r\nprintLog(\"onAttach Called\");\r\n}\r\n\r\n@Override\r\npublic void onCreate(Bundle savedInstanceState) {\r\nsuper.onCreate(savedInstanceState);\r\nprintLog(\"onCreate Called\");\r\n}\r\n\r\n@Override\r\npublic void onDestroy() {\r\nsuper.onDestroy();\r\nprintLog(\"onDestroy Called\");\r\n}\r\n\r\n@Override\r\npublic void onDestroyView() {\r\nsuper.onDestroyView();\r\nprintLog(\"onDestroyView Called\");\r\n}\r\n\r\n@Override\r\npublic void onDetach() {\r\nsuper.onDetach();\r\nprintLog(\"onDetach Called\");\r\n}\r\n\r\n@Override\r\npublic void onPause() {\r\nsuper.onPause();\r\nprintLog(\"onPause Called\");\r\n}\r\n\r\n@Override\r\npublic void onResume() {\r\nsuper.onResume();\r\nprintLog(\"onResume Called\");\r\n}\r\n\r\n@Override\r\npublic void onStart() {\r\nsuper.onStart();\r\nprintLog(\"onStart Called\");\r\n}\r\n\r\n@Override\r\npublic void onStop() {\r\nsuper.onStop();\r\nprintLog(\"onStop Called\");\r\n}\r\n\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 5:\u00a0<\/strong> <\/span>Now create a new xml layout file by right clicking on res\/layout -&gt; New -&gt; Layout Resource File and name it as fragment_test and add the following code in it.<\/p>\n<p>In this step we create a TextView to display a message i.e &#8220;Please Check Logcat.!!!&#8221; on the screen.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;LinearLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"match_parent\"\r\nandroid:orientation=\"vertical\"&gt;\r\n\r\n&lt;!-- Create a TextView --&gt;\r\n\r\n&lt;TextView\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"match_parent\"\r\nandroid:gravity=\"center\"\r\nandroid:text=\"Please Check Logcat.!!!\"\r\nandroid:textColor=\"#000\"\r\nandroid:textSize=\"25sp\" \/&gt;\r\n&lt;\/LinearLayout&gt;\r\n<\/pre>\n<h4><strong>Output:<\/strong><\/h4>\n<p>Check the logcat in Android Studio and you will see Fragment Lifecycle methods in it.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Android, Fragment is a part of an activity which enable more modular activity design. It will not be wrong if we say a fragment is a kind of sub-activity. It represents a behavior or a portion of user interface in an Activity. We can combine multiple Fragments in single Activity to build a multi &hellip; <a href=\"https:\/\/abhiandroid.com\/ui\/fragment-lifecycle-example-android-studio.html\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Fragment Lifecycle Tutorial With Example In Android Studio<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-2118","post","type-post","status-publish","format-standard","hentry","category-archieve"],"acf":[],"psp_head":"<title>Fragment Life Cycle Tutorial With Example In Android Studio \u2013 Abhi Android<\/title>\r\n<meta name=\"description\" content=\"Here is indepth tutorial sharing Fragment Life Cycle with example in Android Studio. Learn all methods onAttach(), onCreate(), OnCreateView(), onActivityCreated(), onStart(), onResume() and few more.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/ui\/fragment-lifecycle-example-android-studio.html\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/posts\/2118","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/comments?post=2118"}],"version-history":[{"count":2,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/posts\/2118\/revisions"}],"predecessor-version":[{"id":2817,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/posts\/2118\/revisions\/2817"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/media?parent=2118"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/categories?post=2118"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/tags?post=2118"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}