{"id":2255,"date":"2016-12-07T10:08:03","date_gmt":"2016-12-07T10:08:03","guid":{"rendered":"http:\/\/abhiandroid.com\/ui\/?page_id=2255"},"modified":"2019-06-12T07:36:24","modified_gmt":"2019-06-12T07:36:24","slug":"fragment","status":"publish","type":"page","link":"https:\/\/abhiandroid.com\/ui\/fragment","title":{"rendered":"Fragment 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 behaviour or a portion of user interface in an Activity. We can combine multiple Fragments in Single Activity to build a multi panel UI and reuse a Fragment in multiple Activities. We always need to embed Fragment in an activity and the fragment lifecycle is directly affected by the host activity&#8217;s lifecycle.<\/p>\n<p>Important Related Read: <a href=\"\/ui\/fragment-lifecycle-example-android-studio.html\">Fragment Lifecycle<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-2235\" src=\"\/ui\/wp-content\/uploads\/2016\/11\/Fragment-Example-Explanation-in-Android.jpg\" alt=\"Fragment Example in Android\" width=\"701\" height=\"460\" srcset=\"https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/11\/Fragment-Example-Explanation-in-Android.jpg 701w, https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/11\/Fragment-Example-Explanation-in-Android-300x197.jpg 300w\" sizes=\"auto, (max-width: 701px) 100vw, 701px\" \/><\/p>\n<p>We can create Fragments by extending\u00a0Fragment\u00a0class or by inserting a Fragment into our Activity layout by declaring the Fragment in the activity&#8217;s layout file, as a\u00a0&lt;fragment&gt;\u00a0element. We can manipulate each Fragment independently, such as add or remove them.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-2237\" src=\"\/ui\/wp-content\/uploads\/2016\/11\/Fragments-in-Android.jpg\" alt=\"Fragments in Android\" width=\"542\" height=\"415\" srcset=\"https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/11\/Fragments-in-Android.jpg 542w, https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/11\/Fragments-in-Android-300x230.jpg 300w\" sizes=\"auto, (max-width: 542px) 100vw, 542px\" \/><\/p>\n<p>While performing Fragment Transaction we can add a Fragment into back stack that&#8217;s managed by the Activity. back stack allow us to reverse a Fragment transaction on pressing Back button of device. For Example if we replace a Fragment and add it in back stack then on pressing the Back button on device it display the previous Fragment.<\/p>\n<hr \/>\n<h4><strong>Some Important Points About Fragment In Android:<\/strong><\/h4>\n<p>1. Fragments were added in Honeycomb version of Android i.e \u00a0API version 11.<\/p>\n<p>2. We can add, replace or remove Fragment\u2019s in an Activity while the activity is running. For performing these operations we need a Layout(Relative Layout, FrameLayout or any other layout) in xml file and then replace that layout with the required Fragment.<\/p>\n<p>3. Fragments has its own layout and its own behaviour with its own life cycle callbacks.<\/p>\n<p>4. Fragment can be used in multiple activities.<\/p>\n<p>5. We can also combine multiple Fragments in a single activity to build a multi-plane UI.<\/p>\n<hr \/>\n<h4><strong>Need Of Fragments In Android:<\/strong><\/h4>\n<p>Before the introduction of Fragment\u2019s we can only show a single Activity on the screen at one given point of time so we were not able to divide the screen and control different parts separately. With the help of Fragment\u2019s we can divide the screens in different parts and controls different parts separately.<\/p>\n<p>By using Fragments we can comprise multiple Fragments in a single Activity. Fragments have their own events, layouts and complete life cycle. It\u00a0provide flexibility and also removed the limitation of single Activity on the screen at a time.<\/p>\n<hr \/>\n<h4><strong>Basic\u00a0Fragment Code\u00a0In XML:<\/strong><\/h4>\n<pre>&lt;fragment\r\nandroid:id=\"@+id\/fragments\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"match_parent\" \/&gt;\r\n<\/pre>\n<hr \/>\n<h4><strong>Create A Fragment Class In Android Studio:<\/strong><\/h4>\n<p>For creating a Fragment firstly we extend the\u00a0Fragment\u00a0class, then override key lifecycle methods to insert our app logic, similar to the way we would with an\u00a0Activity\u00a0class. While creating a Fragment we must use onCreateView() callback to define the layout and in order to run a Fragment.<\/p>\n<pre>import android.os.Bundle;\r\nimport android.support.v4.app.Fragment;\r\nimport android.view.LayoutInflater;\r\nimport android.view.ViewGroup;\r\n\r\npublic class FirstFragment extends Fragment {\r\n@Override\r\npublic View onCreateView(LayoutInflater inflater, ViewGroup container,\r\nBundle savedInstanceState) {\r\n\/\/ Inflate the layout for this fragment\r\nreturn inflater.inflate(R.layout.fragment_first, container, false);\r\n}\r\n}\r\n<\/pre>\n<p>Here the inflater parameter is a LayoutInflater used to inflate the layout,\u00a0container\u00a0parameter \u00a0is the parent\u00a0ViewGroup\u00a0(from the activity&#8217;s layout) in which our Fragment layout will be inserted.<\/p>\n<p>The\u00a0savedInstanceState\u00a0parameter is a\u00a0Bundle\u00a0that provides data about the previous instance of the Fragment. The inflate() method has three arguments first one is the resource layout which we want to inflate, second is the ViewGroup to be the parent of the inflated layout. Passing the\u00a0container\u00a0is important in order for the system to apply layout parameters to the root view of the inflated layout, specified by the parent view in which it&#8217;s going and the third parameter is a boolean value indicating whether the inflated layout should be attached to the\u00a0ViewGroup\u00a0(the second parameter) during inflation.<\/p>\n<hr \/>\n<h4><strong>Implementation of Fragment In Android Require Honeycomb (3.0) or Later:<\/strong><\/h4>\n<p>Fragments were added in in Honeycomb version of Android i.e \u00a0API version 11. There are some primary classes related to Fragment\u2019s are:<\/p>\n<p><span style=\"color: #008000;\"><strong>1. FragmentActivity:<\/strong><\/span> The base class for all activities using compatibility based Fragment (and loader) features.<\/p>\n<p><span style=\"color: #008000;\"><strong>2. Fragment:<\/strong><\/span> The base class for all Fragment definitions<\/p>\n<p><span style=\"color: #008000;\"><strong>3. FragmentManager:<\/strong><\/span> The class for interacting with Fragment objects inside an activity<\/p>\n<p><span style=\"color: #008000;\"><strong>4. FragmentTransaction:<\/strong><\/span> The class for performing an atomic set of Fragment operations such as Replace or Add a Fragment.<\/p>\n<hr \/>\n<h4>Fragment Example\u00a01 In Android Studio:<\/h4>\n<p>Below is the example of Fragment\u2019s. In this example we create two Fragments and load them on the click of Button\u2019s. We display two Button\u2019s and a FrameLayout in our Activity and perform setOnClickListener event on both Button\u2019s. On the click of First Button we replace the First Fragment and on click of Second Button we replace the Second Fragment with the layout(FrameLayout). In the both Fragment\u2019s we display a TextView and a Button and onclick of Button we display the name of the Fragment with the help of Toast.<\/p>\n<p>Below you can download code, see final output\u00a0and read step by step explanation:<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"https:\/\/github.com\/abhisheksaini4\/FragmentExample\" target=\"_blank\" rel=\"nofollow\">Download Code<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-2240\" src=\"\/ui\/wp-content\/uploads\/2016\/11\/Fragments-Example-in-Android-Studio.gif\" alt=\"Fragments Example in Android Studio\" width=\"306\" height=\"453\" \/><\/p>\n<p><span style=\"color: #008000;\"><strong>Step 1:\u00a0<\/strong><\/span>Create a new project and name it FragmentExample<\/p>\n<p><span style=\"color: #008000;\"><strong>Step 2:<\/strong><\/span> \u00a0Open res -&gt; layout -&gt;activity_main.xml (or) main.xml and add following code:<\/p>\n<pre>&lt;LinearLayout 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:orientation=\"vertical\"\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;!-- display two Button's and a FrameLayout to replace the Fragment's\u00a0 --&gt;\r\n&lt;Button\r\nandroid:id=\"@+id\/firstFragment\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:background=\"@color\/button_background_color\"\r\nandroid:text=\"First Fragment\"\r\nandroid:textColor=\"@color\/white\"\r\nandroid:textSize=\"20sp\" \/&gt;\r\n\r\n&lt;Button\r\nandroid:id=\"@+id\/secondFragment\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:layout_marginTop=\"10dp\"\r\nandroid:background=\"@color\/button_background_color\"\r\nandroid:text=\"Second Fragment\"\r\nandroid:textColor=\"@color\/white\"\r\nandroid:textSize=\"20sp\" \/&gt;\r\n\r\n&lt;FrameLayout\r\nandroid:id=\"@+id\/frameLayout\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"match_parent\"\r\nandroid:layout_marginTop=\"10dp\" \/&gt;\r\n&lt;\/LinearLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 3:\u00a0<\/strong><\/span>Open\u00a0 \u00a0src -&gt; package -&gt; MainActivity.java<\/p>\n<p>In this step we open\u00a0MainActivity\u00a0and\u00a0add the code for initiate the Button\u2019s. After that we perform setOnClickListener event on both Button\u2019s. On the click of First Button we replace the First Fragment and on click of Second Button we replace the Second Fragment with the layout(FrameLayout). For replacing a Fragment with FrameLayout firstly we create a Fragment Manager and then begin the transaction using Fragment Transaction and finally replace the Fragment with the layout i.e FrameLayout.<\/p>\n<pre>package com.abhiandroid.fragmentexample;\r\n\r\nimport android.app.Fragment;\r\nimport android.app.FragmentManager;\r\nimport android.app.FragmentTransaction;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.os.Bundle;\r\nimport android.view.View;\r\nimport android.widget.Button;\r\n\r\npublic class MainActivity extends AppCompatActivity {\r\n\r\nButton firstFragment, secondFragment;\r\n\r\n@Override\r\nprotected void onCreate(Bundle savedInstanceState) {\r\nsuper.onCreate(savedInstanceState);\r\nsetContentView(R.layout.activity_main);\r\n\/\/ get the reference of Button's\r\nfirstFragment = (Button) findViewById(R.id.firstFragment);\r\nsecondFragment = (Button) findViewById(R.id.secondFragment);\r\n\r\n\/\/ perform setOnClickListener event on First Button\r\nfirstFragment.setOnClickListener(new View.OnClickListener() {\r\n@Override\r\npublic void onClick(View v) {\r\n\/\/ load First Fragment\r\nloadFragment(new FirstFragment());\r\n}\r\n});\r\n\/\/ perform setOnClickListener event on Second Button\r\nsecondFragment.setOnClickListener(new View.OnClickListener() {\r\n@Override\r\npublic void onClick(View v) {\r\n\/\/ load Second Fragment\r\nloadFragment(new SecondFragment());\r\n}\r\n});\r\n\r\n}\r\n\r\nprivate void loadFragment(Fragment fragment) {\r\n\/\/ create a FragmentManager\r\nFragmentManager fm = getFragmentManager();\r\n\/\/ create a FragmentTransaction to begin the transaction and replace the Fragment\r\nFragmentTransaction fragmentTransaction = fm.beginTransaction();\r\n\/\/ replace the FrameLayout with new Fragment\r\nfragmentTransaction.replace(R.id.frameLayout, fragment);\r\nfragmentTransaction.commit(); \/\/ save the changes\r\n}\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 4:<\/strong><\/span>\u00a0Now we need 2 fragments and 2 xml layouts. So create two fragments by right click on your package folder and create classes and name them as FirstFragment and SecondFragment and add the following code respectively.<\/p>\n<p><strong>FirstFragment.class<\/strong><\/p>\n<p>In this Fragment firstly we inflate the layout and get the reference of Button. After that we perform setOnClickListener event on Button so whenever a user click on the button \u00a0a message \u201cFirst Fragment\u201c is displayed on the screen by using\u00a0 a Toast.<\/p>\n<pre>package com.abhiandroid.fragmentexample;\r\n\r\nimport android.app.Fragment;\r\nimport android.os.Bundle;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\nimport android.widget.Button;\r\nimport android.widget.Toast;\r\n\r\npublic class FirstFragment extends Fragment {\r\n\r\n\r\nView view;\r\nButton firstButton;\r\n\r\n@Override\r\npublic View onCreateView(LayoutInflater inflater, ViewGroup container,\r\nBundle savedInstanceState) {\r\n\/\/ Inflate the layout for this fragment\r\nview = inflater.inflate(R.layout.fragment_first, container, false);\r\n\/\/ get the reference of Button\r\nfirstButton = (Button) view.findViewById(R.id.firstButton);\r\n\/\/ perform setOnClickListener on first Button\r\nfirstButton.setOnClickListener(new View.OnClickListener() {\r\n@Override\r\npublic void onClick(View v) {\r\n\/\/ display a message by using a Toast\r\nToast.makeText(getActivity(), \"First Fragment\", Toast.LENGTH_LONG).show();\r\n}\r\n});\r\nreturn view;\r\n}\r\n}\r\n<\/pre>\n<p><strong>SecondFragment.class<\/strong><\/p>\n<p>In this Fragment firstly we inflate the layout and get the reference of Button. After that we perform setOnClickListener event on Button so whenever a user click on the button \u00a0a message \u201cSecond Fragment\u201c is displayed on the screen by using\u00a0 a Toast.<\/p>\n<pre>package com.abhiandroid.fragmentexample;\r\n\r\nimport android.app.Fragment;\r\nimport android.os.Bundle;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\nimport android.widget.Button;\r\nimport android.widget.Toast;\r\n\r\n\r\npublic class SecondFragment extends Fragment {\r\n\r\nView view;\r\nButton secondButton;\r\n\r\n@Override\r\npublic View onCreateView(LayoutInflater inflater, ViewGroup container,\r\nBundle savedInstanceState) {\r\n\/\/ Inflate the layout for this fragment\r\nview = inflater.inflate(R.layout.fragment_second, container, false);\r\n\/\/ get the reference of Button\r\nsecondButton = (Button) view.findViewById(R.id.secondButton);\r\n\/\/ perform setOnClickListener on second Button\r\nsecondButton.setOnClickListener(new View.OnClickListener() {\r\n@Override\r\npublic void onClick(View v) {\r\n\/\/ display a message by using a Toast\r\nToast.makeText(getActivity(), \"Second Fragment\", Toast.LENGTH_LONG).show();\r\n}\r\n});\r\nreturn view;\r\n}\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 5:\u00a0<\/strong><\/span>\u00a0Now create 2 xml layouts by\u00a0right clicking on res\/layout -&gt; New -&gt; Layout Resource\u00a0File\u00a0and name them as fragment_first and fragment_second and add the following code in respective files.<\/p>\n<p>Here we will design the basic simple UI by using TextView and Button in both xml\u2019s.<\/p>\n<p><strong>fragment_first.xml<\/strong><\/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\ntools:context=\"com.abhiandroid.fragmentexample.FirstFragment\"&gt;\r\n\r\n&lt;!--TextView and Button displayed in First Fragment --&gt;\r\n&lt;TextView\r\nandroid:layout_width=\"wrap_content\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:layout_centerHorizontal=\"true\"\r\nandroid:layout_marginTop=\"100dp\"\r\nandroid:text=\"This is First Fragment\"\r\nandroid:textColor=\"@color\/black\"\r\nandroid:textSize=\"25sp\" \/&gt;\r\n\r\n&lt;Button\r\nandroid:id=\"@+id\/firstButton\"\r\nandroid:layout_width=\"fill_parent\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:layout_centerInParent=\"true\"\r\nandroid:layout_marginLeft=\"20dp\"\r\nandroid:layout_marginRight=\"20dp\"\r\nandroid:background=\"@color\/green\"\r\nandroid:text=\"First Fragment\"\r\nandroid:textColor=\"@color\/white\"\r\nandroid:textSize=\"20sp\"\r\nandroid:textStyle=\"bold\" \/&gt;\r\n&lt;\/RelativeLayout&gt;\r\n<\/pre>\n<p><strong>fragment_second.xml<\/strong><\/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\ntools:context=\"com.abhiandroid.fragmentexample.SecondFragment\"&gt;\r\n\r\n&lt;!--TextView and Button displayed in Second Fragment --&gt;\r\n&lt;TextView\r\nandroid:layout_width=\"wrap_content\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:layout_centerHorizontal=\"true\"\r\nandroid:layout_marginTop=\"100dp\"\r\nandroid:text=\"This is Second Fragment\"\r\nandroid:textColor=\"@color\/black\"\r\nandroid:textSize=\"25sp\" \/&gt;\r\n\r\n&lt;Button\r\nandroid:id=\"@+id\/secondButton\"\r\nandroid:layout_width=\"fill_parent\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:layout_centerInParent=\"true\"\r\nandroid:layout_marginLeft=\"20dp\"\r\nandroid:layout_marginRight=\"20dp\"\r\nandroid:background=\"@color\/green\"\r\nandroid:text=\"Second Fragment\"\r\nandroid:textColor=\"@color\/white\"\r\nandroid:textSize=\"20sp\"\r\nandroid:textStyle=\"bold\" \/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 6:<\/strong><\/span> Open res -&gt;values -&gt;colors.xml<\/p>\n<p>In this step we define the color\u2019s that used in our xml file.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;resources&gt;\r\n&lt;!-- color's used in our project --&gt;\r\n&lt;color name=\"black\"&gt;#000&lt;\/color&gt;\r\n&lt;color name=\"green\"&gt;#0f0&lt;\/color&gt;\r\n&lt;color name=\"white\"&gt;#fff&lt;\/color&gt;\r\n&lt;color name=\"button_background_color\"&gt;#925&lt;\/color&gt;\r\n&lt;\/resources&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 7:<\/strong><\/span> Open\u00a0AndroidManifest.xml<\/p>\n<p>In this step we show the Android Manifest file in which do nothing because we\u00a0 need only one Activitty i.e MainActivity which is already defined in it. In our project\u00a0 we create two Fragment\u2019s but we don\u2019t need to define the Fragment\u2019s in manifest because Fragment is a part of an Activity.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;manifest xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\npackage=\"com.abhiandroid.fragmentexample\" &gt;\r\n\r\n&lt;application\r\nandroid:allowBackup=\"true\"\r\nandroid:icon=\"@mipmap\/ic_launcher\"\r\nandroid:label=\"@string\/app_name\"\r\nandroid:theme=\"@style\/AppTheme\" &gt;\r\n&lt;activity\r\nandroid:name=\".MainActivity\"\r\nandroid:label=\"@string\/app_name\" &gt;\r\n&lt;intent-filter&gt;\r\n&lt;action android:name=\"android.intent.action.MAIN\" \/&gt;\r\n\r\n&lt;category android:name=\"android.intent.category.LAUNCHER\" \/&gt;\r\n&lt;\/intent-filter&gt;\r\n&lt;\/activity&gt;\r\n&lt;\/application&gt;\r\n&lt;\/manifest&gt;<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 8:<\/strong><\/span> Now run the App and you will two button. Clicking on first button shows First Fragment and on click of Second Button shows\u00a0the Second Fragment which is actually replacing\u00a0layout(FrameLayout).<\/p>\n<hr \/>\n<h4><strong>Fragment Example 2 In Android Studio:<\/strong><\/h4>\n<p>Below is the example of Simple Fragment. In this example we create a simple Fragment and display it in our Activity by declaring a &lt;fragment&gt; element in our xml file. We also display a Button in our activity\u2019s xml and perform click event so whenever a user click on it a message is displayed on the screen by using a Toast. In the Fragment we display a TextView and a Button and perform click event of Button so whenever a user click on the Button a message is displayed on the screen with the help of Toast.<\/p>\n<p>Below you can download code, see final output\u00a0and read step by step explanation:<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"https:\/\/github.com\/abhisheksaini4\/FragmentExample\" target=\"_blank\" rel=\"nofollow\">Download Code<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-2241\" src=\"\/ui\/wp-content\/uploads\/2016\/11\/Fragment-Example-2-In-Android-Studio.gif\" alt=\"Fragment Example 2 in Android Studio\" width=\"303\" height=\"433\" \/><\/p>\n<p><span style=\"color: #008000;\"><strong>Step 1:<\/strong><\/span>\u00a0Create a new project and name it FragmentExample<\/p>\n<p><span style=\"color: #008000;\"><strong>Step 2:<\/strong><\/span> \u00a0Open res -&gt; layout -&gt;activity_main.xml (or) main.xml and add following code:<\/p>\n<pre>&lt;LinearLayout 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:orientation=\"vertical\"\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;!-- display a Button and a Fragment\u00a0 --&gt;\r\n\r\n&lt;Button\r\nandroid:id=\"@+id\/activity_button\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:layout_marginTop=\"10dp\"\r\nandroid:background=\"@color\/button_background_color\"\r\nandroid:text=\"Activity's Button\"\r\nandroid:textColor=\"@color\/white\"\r\nandroid:textSize=\"20sp\" \/&gt;\r\n\r\n&lt;fragment\r\nandroid:id=\"@+id\/fragments\"\r\nandroid:name=\"com.abhiandroid.fragmentexample.SimpleFragment\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"match_parent\"\r\nandroid:layout_marginTop=\"10dp\" \/&gt;\r\n&lt;\/LinearLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 3:<\/strong><\/span>\u00a0Open\u00a0 \u00a0src -&gt; package -&gt; MainActivity.java<\/p>\n<p>In this step we open\u00a0MainActivity\u00a0and\u00a0add the code for initiate the Button. After that we perform setOnClickListener \u00a0on Button so whenever a user click on Button a message is displayed on the screen with the help of Toast.<\/p>\n<pre>package com.abhiandroid.fragmentexample;\r\n\r\nimport android.app.Fragment;\r\nimport android.app.FragmentManager;\r\nimport android.app.FragmentTransaction;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.os.Bundle;\r\nimport android.view.View;\r\nimport android.widget.Button;\r\nimport android.widget.Toast;\r\n\r\npublic class MainActivity extends AppCompatActivity {\r\n\r\nButton activityButton;\r\n\r\n@Override\r\nprotected void onCreate(Bundle savedInstanceState) {\r\nsuper.onCreate(savedInstanceState);\r\nsetContentView(R.layout.activity_main);\r\n\/\/ get the reference of Button\r\nactivityButton = (Button) findViewById(R.id.activity_button);\r\n\r\n\/\/ perform setOnClickListener event on Button\r\nactivityButton.setOnClickListener(new View.OnClickListener() {\r\n@Override\r\npublic void onClick(View v) {\r\n\/\/ display a message by using a Toast\r\nToast.makeText(getApplicationContext(), \"Activity's Button\", Toast.LENGTH_LONG).show();\r\n}\r\n});\r\n}\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 4:<\/strong><\/span>\u00a0Now we create a fragment by right click on your package folder and create classes and name it SimpleFragment and add the following code.<\/p>\n<p>In this Fragment firstly we inflate the layout and get the reference of Button. After that we perform setOnClickListener event on Button so whenever a user click on the button \u00a0a message \u201cFragment\u2019s Button\u201c is displayed on the screen by using\u00a0 a Toast.<\/p>\n<pre>package com.abhiandroid.fragmentexample;\r\n\r\nimport android.app.Fragment;\r\nimport android.os.Bundle;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\nimport android.widget.Button;\r\nimport android.widget.Toast;\r\n\r\n\r\npublic class SimpleFragment extends Fragment {\r\n\r\nView view;\r\nButton firstButton;\r\n\r\n@Override\r\npublic View onCreateView(LayoutInflater inflater, ViewGroup container,\r\nBundle savedInstanceState) {\r\n\/\/ Inflate the layout for this fragment\r\nview = inflater.inflate(R.layout.fragment_simple, container, false);\r\n\/\/ get the reference of Button\r\nfirstButton = (Button) view.findViewById(R.id.firstButton);\r\n\/\/ perform setOnClickListener on first Button\r\nfirstButton.setOnClickListener(new View.OnClickListener() {\r\n@Override\r\npublic void onClick(View v) {\r\n\/\/ display a message by using a Toast\r\nToast.makeText(getActivity(), \"Fragment's Button\", Toast.LENGTH_LONG).show();\r\n}\r\n});\r\nreturn view;\r\n}\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 5:\u00a0<\/strong><\/span>\u00a0Now create a xml layouts by\u00a0right clicking on res\/layout -&gt; New -&gt; Layout Resource\u00a0File\u00a0and name fragment_simple and add the following code in it.<\/p>\n<p>Here we will design the basic simple UI by using TextView and Button<\/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\ntools:context=\"com.abhiandroid.fragmentexample.SimpleFragment\"&gt;\r\n\r\n&lt;!--TextView and Button displayed in Simple Fragment --&gt;\r\n&lt;TextView\r\nandroid:layout_width=\"wrap_content\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:layout_centerHorizontal=\"true\"\r\nandroid:layout_marginTop=\"100dp\"\r\nandroid:text=\"Simple Fragment\"\r\nandroid:textColor=\"@color\/black\"\r\nandroid:textSize=\"25sp\" \/&gt;\r\n\r\n&lt;Button\r\nandroid:id=\"@+id\/firstButton\"\r\nandroid:layout_width=\"fill_parent\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:layout_centerInParent=\"true\"\r\nandroid:layout_marginLeft=\"20dp\"\r\nandroid:layout_marginRight=\"20dp\"\r\nandroid:background=\"@color\/green\"\r\nandroid:text=\"Fragment's Button\"\r\nandroid:textColor=\"@color\/white\"\r\nandroid:textSize=\"20sp\"\r\nandroid:textStyle=\"bold\" \/&gt;\r\n&lt;\/RelativeLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 6:<\/strong><\/span> Open res -&gt;values -&gt;colors.xml<\/p>\n<p>In this step we define the color\u2019s that used in our xml file.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;resources&gt;\r\n&lt;!-- color's used in our project --&gt;\r\n&lt;color name=\"black\"&gt;#000&lt;\/color&gt;\r\n&lt;color name=\"green\"&gt;#0f0&lt;\/color&gt;\r\n&lt;color name=\"white\"&gt;#fff&lt;\/color&gt;\r\n&lt;color name=\"button_background_color\"&gt;#925&lt;\/color&gt;\r\n&lt;\/resources&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 7:<\/strong> <\/span>Open\u00a0AndroidManifest.xml<\/p>\n<p>In this step we show the Android Manifest file in which do nothing because we\u00a0 need only one Activitty i.e MainActivity which is already defined in it. In our project\u00a0 we a Fragment\u2019s but we don\u2019t need to define the it in manifest because Fragment is a part of an Activity.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;manifest xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\npackage=\"com.abhiandroid.fragmentexample\" &gt;\r\n\r\n&lt;application\r\nandroid:allowBackup=\"true\"\r\nandroid:icon=\"@mipmap\/ic_launcher\"\r\nandroid:label=\"@string\/app_name\"\r\nandroid:theme=\"@style\/AppTheme\" &gt;\r\n&lt;activity\r\nandroid:name=\".MainActivity\"\r\nandroid:label=\"@string\/app_name\" &gt;\r\n&lt;intent-filter&gt;\r\n&lt;action android:name=\"android.intent.action.MAIN\" \/&gt;\r\n\r\n&lt;category android:name=\"android.intent.category.LAUNCHER\" \/&gt;\r\n&lt;\/intent-filter&gt;\r\n&lt;\/activity&gt;\r\n&lt;\/application&gt;\r\n\r\n&lt;\/manifest&gt;\r\n<\/pre>\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 behaviour 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\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Fragment Tutorial With Example In Android Studio<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"closed","template":"home.php","meta":{"_acf_changed":false,"footnotes":""},"class_list":["post-2255","page","type-page","status-publish","hentry"],"acf":[],"psp_head":"<title>Fragments Tutorial With Example In Android Studio \u2013 Abhi Android<\/title>\r\n<meta name=\"description\" content=\"Understand the concept of Fragments following our tutorial with 2 examples in Android Studio. We also explain need, class and other important activity about it.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/ui\/fragment\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/pages\/2255","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/types\/page"}],"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=2255"}],"version-history":[{"count":3,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/pages\/2255\/revisions"}],"predecessor-version":[{"id":2783,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/pages\/2255\/revisions\/2783"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/media?parent=2255"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}