{"id":81420,"date":"2021-07-02T09:00:29","date_gmt":"2021-07-02T03:30:29","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=81420"},"modified":"2024-08-02T21:13:41","modified_gmt":"2024-08-02T15:43:41","slug":"android-fragments","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/","title":{"rendered":"Android Fragments"},"content":{"rendered":"<p>This article will help you understand what fragments are and the several types of fragments in android. You will also know how to create a fragment and communicate between the fragments and the activities. You will get to see the lifecycle and the various methods involved in the fragments.<\/p>\n<p>Further, we will implement the concept through an application that will make your ideas more clear.<\/p>\n<h2>What are Fragments in Android?<\/h2>\n<p>Fragments are like sub-activities of an Android Activity. In other words, you can think of it as a part of an activity. It\u2019s a graphical user interface that allows users to interact but depends on an activity for its existence.<\/p>\n<p>An activity can hold many fragments inside it. Fragments have their lifecycle, but their life cycle is dependent on the parent activity\u2019s lifecycle. If the action where the fragment resides is destroyed, then even the fragment gets destroyed.<\/p>\n<p>Here a question may arise to you. If a fragment is so dependent on the activity, then why do we use it in android?<br \/>\nLet\u2019s see the need for fragments that will automatically answer the above question.<\/p>\n<h2>Needs of Android Fragments<\/h2>\n<p>Fragments are generally used to make a lightweight and smooth user interface. Fragments can be dynamically added and deleted from an activity. The flexibility of fragments allows several kinds of UI to be possible.<br \/>\nYou can create a custom tabbed layout or swiping tab layout using fragments. Fragments have their events and allow you to perform various tasks through fragments.<br \/>\nFragment layouts are customizable. We can add as many text views, image views, buttons, etc.<\/p>\n<h2>Types of Fragments in Android<\/h2>\n<p>Fragments are basically of three types:<\/p>\n<h3>1. Single Fragments in Android<\/h3>\n<p>Here, you can only see one fragment on the entire screen. It is primarily seen in handheld devices like smartphones. This type of fragment is useful for activities that only require one main view, such as a detailed view of an item.<\/p>\n<h3>2. List Fragments in Android<\/h3>\n<p>Here, the fragments are in the form of a list, and the user can pick the fragment he wishes to view. This type of fragment is often used in combination with a detail fragment to display a list of items and their details on selection.<\/p>\n<h3>3. Fragment Transactions in Android<\/h3>\n<p>Using this type of fragment, you can switch between fragments.<\/p>\n<h2>How Android Fragments interact with activity in various devices<\/h2>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Fragments-interact-with-activity-in-various-devices.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81666\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Fragments-interact-with-activity-in-various-devices.jpg\" alt=\"Fragments interact with activity in various devices\" width=\"900\" height=\"600\" \/><\/a><\/p>\n<p>So to understand this, let\u2019s take the example shown in the above picture. Here you can see we are considering two devices: Tablet and a Handset. Let\u2019 see how fragments interact through activity in both devices.<\/p>\n<p>In Tablet, we have only one activity called Activity 1. In this activity, we have two fragments Fragment A and Fragment B. If the user selects something in Fragment A, then that is displayed on Fragment B. Here, we don\u2019t require another activity to perform this thing.<\/p>\n<p>Whereas in the handset, we require two activities as the device\u2019s screen size is comparatively tiny than tablets. Hence we would need two activities to perform the same task. In Activity 1, we have fragment A where the user selects something. In Activity 2, we have fragment B, where the user can view his selection.<\/p>\n<h2>Lifecycle of Fragments in Android<\/h2>\n<p>Fragments depend upon the activity for its existence and have a lifecycle similar to Android Activity. Below is an image that summarizes the Fragment Lifecycle.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Lifecycle-of-Fragments.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81667\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Lifecycle-of-Fragments.jpg\" alt=\"Lifecycle of Fragments in Android\" width=\"1200\" height=\"811\" \/><\/a><\/p>\n<h2>Methods of Fragments in Android<\/h2>\n<p>Following are the methods that are implemented depending on the requirement we have. All these methods contribute to the proper functioning of a fragment. Let\u2019s see each of them in detail.<\/p>\n<h3>1. onAttach()<\/h3>\n<p>To initialize a fragment with the respective activity, we use the above method. Using this method, the fragment gets fully initialized. It is called once the fragment is associated with its activity, allowing the fragment to interact with the activity context and access its properties.<\/p>\n<h3>2. onCreate()<\/h3>\n<p>This method is used to create a fragment and initialize the necessary components. We may want to retain these essential components even if the fragment is paused or stopped and then resumed. It is called to perform the initial setup, such as inflating views and setting up resources.<\/p>\n<h3>3. onCreateView()<\/h3>\n<p>This method is used to return the UI layout of the fragment to the user. This method is invoked at the time when the fragment is created. If you don\u2019t have any design with your fragment then just return null.<\/p>\n<h3>4. onActivityCreated()<\/h3>\n<p>This method is invoked after the onCreateView(). This method signifies that the activity is ready to host your fragment. After this method is invoked, we can access the fragment view by using findViewById().<\/p>\n<h3>5. onStart()<\/h3>\n<p>This method is invoked immediately after the fragment is visible on the user\u2019s device. It marks the point where the fragment becomes visible and interactive to the user, often used to initialize components that require user input.<\/p>\n<h3>6. onResume()<\/h3>\n<p>This method is invoked immediately when the fragment comes back into focus. It signifies that the fragment is now active and the user can interact with it. This method is typically used to resume any paused tasks or animations.<\/p>\n<h3>7. onPause()<\/h3>\n<p>This method is invoked whenever the fragment goes out of focus or is inactive for some duration. It allows you to save any state changes or pause ongoing tasks that should not continue while the fragment is not in the foreground.<\/p>\n<h3>8. onStop()<\/h3>\n<p>This method is invoked when the fragment is not visible to the user anymore.<\/p>\n<h3>9. onDestroyView()<\/h3>\n<p>This method is invoked to clear up the resources used by the fragment. It is called just before the fragment is going to be destroyed. It allows you to clean up resources related to the fragment&#8217;s view, such as bitmap recycling or stopping services.<\/p>\n<h3>10. onDestroy()<\/h3>\n<p>This method is invoked to destroy the fragment and clean up its state. It is the final cleanup call before the fragment is completely removed from memory. Use this method to release resources and save any persistent state.<\/p>\n<h3>11. onDetach()<\/h3>\n<p>This method is invoked to detach a fragment from host activity. It marks the end of the fragment&#8217;s association with its activity and provides an opportunity to perform final cleanup before the fragment is destroyed.<\/p>\n<h2>How to use Android Fragments?<\/h2>\n<p>Fragments can be used in a project by following the below steps:<\/p>\n<ul>\n<li>Decide the number of fragments you require<\/li>\n<li>Go ahead and create an XML layout file for each such fragment.<\/li>\n<li>Create a class extending Fragment class and then link the class with the layout created.<\/li>\n<li>Now use the above-discussed methods based on your needs.<\/li>\n<li>Finally, come back to the Main Activity and edit the file adding the fragments to your activity.<\/li>\n<\/ul>\n<h2>Android Fragments with Activity<\/h2>\n<p>We know that fragments are required to be present in an activity. A fragment individually can\u2019t exist, and hence we should know how to place a fragment with an activity. There are two ways to do this:<\/p>\n<h3>1. Static method<\/h3>\n<p>Using this method, you can place the fragment through the XML file. The demerit of this method is you can\u2019t change the fragment on runtime. If you wish to change the fragment with another, you need to edit the XML code again.<\/p>\n<p>While placing the fragment you should ensure that the fragment class extends FragmentActivity or AppCompatActivity.<\/p>\n<p>Below is an implementation of the same.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;LinearLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    android:orientation=\"vertical\" &gt;\r\n\r\n    &lt;fragment\r\n        android:name=\"com.TechVidvan.android.MyFragment\"\r\n        android:id=\"@+id\/static_fragment\"\r\n        android:layout_width=\"match_parent\" \r\n        android:layout_height=\"match_parent\" \/&gt;\r\n\r\n&lt;\/LinearLayout&gt;\r\n<\/pre>\n<h3>2. Dynamic method<\/h3>\n<p>Unlike the static method here, you can change the fragments on runtime. You need to add a frame layout, and then through fragment transaction, you can place fragments during runtime. Below is an implementation of the same.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;LinearLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    android:orientation=\"vertical\" &gt;\r\n  &lt;FrameLayout\r\n       android:id=\"@+id\/fragment_placeholder\"\r\n       android:layout_width=\"match_parent\"\r\n       android:layout_height=\"match_parent\"&gt;\r\n  &lt;\/FrameLayout&gt;\r\n&lt;\/LinearLayout&gt;\r\n<\/pre>\n<p>Now to create the fragment transaction, you can use the below code.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"> val transaction = fragmentSupportManager.beginTransaction()\r\n transaction.replace(R.id.host,new TechVidvanFragment())\r\n transaction.commit()\r\n<\/pre>\n<h2>Fragment Instance in Android<\/h2>\n<p>We know that fragment is placed in an activity. To find a fragment in your project, you have several methods. You can use the below to locate the required fragment:<\/p>\n<h3>1. By ID:<\/h3>\n<p>Using this, we can find the fragment based on its ID. You need to use the findFragmentByID() method in this case.<\/p>\n<h3>2. By Tag:<\/h3>\n<p>Using this, we can find the fragment based on its name. You need to use the findFragmentByName() method in this case.<\/p>\n<h3>3. By Pager<\/h3>\n<p>Using this, we can find the fragment based on the view pager on which the fragment is registered. You need to use the getRegisteredFragment() method in this case.<\/p>\n<h2>Android Fragment and Activity Communication<\/h2>\n<p>The fragment is a part of the activity, and if in case the fragment needs to communicate to the other fragments. Then it can\u2019t do it directly. It needs to communicate through its parent activity to perform a task.<\/p>\n<p>So, it becomes essential for us to understand how a fragment can communicate with its root activity. Following are the methods which you can do to achieve the task.<\/p>\n<h3>1. View Model<\/h3>\n<p>Whenever we want to share data or communicate between the fragments, we can create a standard view model. The view model allows multiple fragments to interact and communicate.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class TechVidvanViewModel : ViewModel() {\r\nprivate val mutable_Item = MutableLiveData&lt;Item&gt;()\r\nval selectedItem: LiveData&lt;Item&gt; get() = mutable_item\r\n\r\nfun selectItem(item: Item) {\r\nmutable_item.value = item\r\n}\r\n}<\/pre>\n<h3>2. Interface<\/h3>\n<p>Using an interface also you can connect multiple fragments. You just need to create an interface in your first fragment. Now, you need to implement the designed interface in your activity. Directly by calling the other fragment from your activity, you can simply connect the interface.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class FragmentOne : Fragment() {\r\n\r\n        lateinit var listener: TextClickedListener\r\n\r\n        \/\/defining Interface\r\n        interface TextClickedListener {\r\n            fun sendText(text: String)\r\n        }\r\n\r\n        fun setOnTextClickedListener(callback: TextClickedListener) {\r\n            this.listener = callback\r\n        }\r\n\r\n    }\r\n}\r\n<\/pre>\n<p><span style=\"font-weight: 400;\">Now you need to implement the above interface in your Main Activity. You can do that using the below code.<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class MainActivity :Activity(), FragmentOne.TextClicked {\r\n    fun onAttachFragment(fragment: Fragment) {\r\n        if (fragment is FragmentOne) {\r\n            fragment.setOnTextClickedListener(this)\r\n        }\r\n    }\r\n    override fun sendText(text: String) {\r\n        \/\/ Call FragmentTwo\r\n        val callingFragmentTwo = getSupportFragmentManager().findFragmentById(R.id.fragment_two) as FragmentTwo\r\n        \/\/calling the updateMsg method of the FragmentTwo\r\n        callingFragmentTwo.updateMsg(text)\r\n    }\r\n}\r\n<\/pre>\n<p><span style=\"font-weight: 400;\">Now you can create the updateMsg() method in your Fragment Two, and this will do your task.<\/span><\/p>\n<h2>Nesting Fragments within Fragment in Android<\/h2>\n<p>Sometimes there can be a need to have a fragment inside another fragment. This can be achieved by simply placing another FrameLayout inside the existing layout of the fragment. This helps you to keep a fragment inside another.<br \/>\nThis process is also known as Fragment Nesting.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&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&lt;TextView\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:text=\"The root Fragment\" \/&gt;\r\n&lt;FrameLayout\r\nandroid:id=\"@+id\/child_fragmentr\"\r\nandroid:layout_width=\u201d200dp\"\r\nandroid:layout_height=\"400dp\" \/&gt;\r\n&lt;\/LinearLayout&gt;<\/pre>\n<p>So, here you can see the linear layout is the layout of the root fragment. In this root fragment, we are creating a child fragment using the frame layout container.<\/p>\n<h2>Implementation of Android Fragments<\/h2>\n<p>Following are the steps using which you can create fragments in Android. We will show you how to create a layout similar to WhatsApp, having three fragments: Chats, Status, Calls.<\/p>\n<p><strong>1:<\/strong> Open your Android Studio.<\/p>\n<p><strong>2: <\/strong>Click on Create New Project.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/fragment_creation_1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81678\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/fragment_creation_1.png\" alt=\"Android Fragment\" width=\"954\" height=\"690\" \/><\/a><\/p>\n<p><strong>3: <\/strong>Select Empty Activity and proceed.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/fragment_creation_2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81670\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/fragment_creation_2.png\" alt=\"Android Project\" width=\"1848\" height=\"1048\" \/><\/a><\/p>\n<p><strong>4: <\/strong>Enter your application name. In my case, it\u2019s \u201cTechVidvanFragments.\u201d Next, select Kotlin from the dropdown. For the API level, select API 22 for now.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/fragment_creation_3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81671\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/fragment_creation_3.png\" alt=\"Android Fragment Creation\" width=\"1848\" height=\"1044\" \/><\/a><\/p>\n<p><strong>5: <\/strong>Now open your app-level Gradle file and paste the below dependency in the dependencies. Now click on sync.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/Add Material Dependency\r\n    implementation 'com.google.android.material:material:1.3.0'\r\n<\/pre>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/fragment_creation_4.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81672\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/fragment_creation_4.png\" alt=\"Android Dependency\" width=\"1844\" height=\"1048\" \/><\/a><\/p>\n<p><strong>6: <\/strong>Now go to res&#8212;&gt; values &#8212;&gt;themes and paste the below code.<\/p>\n<p><strong>themes.xml<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;resources xmlns:tools=\"http:\/\/schemas.android.com\/tools\"&gt;\r\n    &lt;!-- Base application theme. --&gt;\r\n    &lt;style name=\"Theme.TechVidvanFragment\" parent=\"Theme.MaterialComponents.DayNight.NoActionBar\"&gt;\r\n        &lt;!-- Primary brand color. --&gt;\r\n        &lt;item name=\"colorPrimary\"&gt;@color\/green&lt;\/item&gt;\r\n        &lt;item name=\"colorPrimaryVariant\"&gt;@color\/green&lt;\/item&gt;\r\n        &lt;item name=\"colorOnPrimary\"&gt;@color\/white&lt;\/item&gt;\r\n        &lt;!-- Secondary brand color. --&gt;\r\n        &lt;item name=\"colorSecondary\"&gt;@color\/teal_200&lt;\/item&gt;\r\n        &lt;item name=\"colorSecondaryVariant\"&gt;@color\/teal_700&lt;\/item&gt;\r\n        &lt;item name=\"colorOnSecondary\"&gt;@color\/black&lt;\/item&gt;\r\n        &lt;!-- Status bar color. --&gt;\r\n        &lt;item name=\"android:statusBarColor\" tools:targetApi=\"l\"&gt;?attr\/colorPrimaryVariant&lt;\/item&gt;\r\n        &lt;!-- Customize your theme here. --&gt;\r\n    &lt;\/style&gt;\r\n&lt;\/resources&gt;\r\n<\/pre>\n<p><strong>7:<\/strong> Now open your activity_main.xml file and copy-paste the below code.<\/p>\n<p><strong>activity_main.xml<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;RelativeLayout\r\n    xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:app=\"http:\/\/schemas.android.com\/apk\/res-auto\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    tools:context=\".MainActivity\"&gt;\r\n\r\n    &lt;com.google.android.material.appbar.AppBarLayout\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:id=\"@+id\/top_bar\"&gt;\r\n\r\n        &lt;com.google.android.material.tabs.TabLayout\r\n            android:id=\"@+id\/tabs\"\r\n            android:layout_width=\"match_parent\"\r\n            android:layout_height=\"wrap_content\"\r\n            app:tabBackground=\"@color\/green\"\r\n            app:tabGravity=\"fill\"\r\n            app:tabInlineLabel=\"true\"\r\n            app:tabMode=\"fixed\"\r\n            app:tabTextColor=\"@color\/d_green\"\r\n            app:tabSelectedTextColor=\"@color\/white\"\r\n            \/&gt;\r\n    &lt;\/com.google.android.material.appbar.AppBarLayout&gt;\r\n\r\n    &lt;androidx.viewpager.widget.ViewPager\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"match_parent\"\r\n        android:id=\"@+id\/view_pager\"\r\n        android:layout_below=\"@+id\/top_bar\"\/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;<\/pre>\n<p><strong>8: <\/strong><span style=\"font-weight: 400;\">Now, go to your project structure. Select your package and right-click. Then select New&#8212;&gt; Fragments &#8212;&gt; Fragments(Blank).\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400;\">You will see a screen like below. Keep the name as ChatsFragment and proceed.\u00a0<\/span><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/fragment_creation_5.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81673\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/fragment_creation_5.png\" alt=\"Android Fragment Creation\" width=\"1846\" height=\"1044\" \/><\/a><\/p>\n<p><span style=\"font-weight: 400;\">Similarly, create two other fragments named StatusFragment and CallsFragment. <\/span><span style=\"font-weight: 400;\">Now copy the below codes in respective fragments and their layout files.<\/span><\/p>\n<p><strong>fragment_chats.xml<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;FrameLayout \r\n    xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    tools:context=\".ChatsFragment\"&gt;\r\n    \r\n    &lt;TextView\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"match_parent\"\r\n        android:gravity=\"center\"\r\n        android:textSize=\"40sp\"\r\n        android:textColor=\"@color\/black\"\r\n        android:text=\"TechVidvan Chat Fragment\" \/&gt;\r\n\r\n&lt;\/FrameLayout&gt;\r\n<\/pre>\n<p><strong>ChatsFragemnt.kt<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.example.techvidvanfragment\r\n\r\nimport android.os.Bundle\r\nimport androidx.fragment.app.Fragment\r\nimport android.view.LayoutInflater\r\nimport android.view.View\r\nimport android.view.ViewGroup\r\n\r\nclass ChatsFragment : Fragment() {\r\n\r\n    override fun onCreate(savedInstanceState: Bundle?) {\r\n        super.onCreate(savedInstanceState)\r\n        arguments?.let {\r\n        }\r\n    }\r\n\r\n    override fun onCreateView(\r\n        inflater: LayoutInflater, container: ViewGroup?,\r\n        savedInstanceState: Bundle?\r\n    ): View? {\r\n        \/\/ Inflate the layout for this fragment\r\n        return inflater.inflate(R.layout.fragment_chats, container, false)\r\n    }\r\n}<\/pre>\n<p><b>fragment_status.xml<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;FrameLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    tools:context=\".StatusFragment\"&gt;\r\n\r\n    &lt;TextView\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"match_parent\"\r\n        android:gravity=\"center\"\r\n        android:textSize=\"40sp\"\r\n        android:textColor=\"@color\/black\"\r\n        android:text=\"TechVidvan Status Fragment\" \/&gt;\r\n\r\n&lt;\/FrameLayout&gt;<\/pre>\n<p><b>StatusFragemnt.kt<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.example.techvidvanfragment\r\n\r\nimport android.os.Bundle\r\nimport androidx.fragment.app.Fragment\r\nimport android.view.LayoutInflater\r\nimport android.view.View\r\nimport android.view.ViewGroup\r\n\r\nclass StatusFragment : Fragment() {\r\n\r\n    override fun onCreate(savedInstanceState: Bundle?) {\r\n        super.onCreate(savedInstanceState)\r\n        arguments?.let {\r\n        }\r\n    }\r\n\r\n    override fun onCreateView(\r\n        inflater: LayoutInflater, container: ViewGroup?,\r\n        savedInstanceState: Bundle?\r\n    ): View? {\r\n        \/\/ Inflate the layout for this fragment\r\n        return inflater.inflate(R.layout.fragment_status, container, false)\r\n    }\r\n\r\n}<\/pre>\n<p><b>fragment_calls.xml<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;FrameLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    tools:context=\".CallsFragment\"&gt;\r\n\r\n    &lt;TextView\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"match_parent\"\r\n        android:gravity=\"center\"\r\n        android:textSize=\"40sp\"\r\n        android:textColor=\"@color\/black\"\r\n        android:text=\"TechVidvan Calls Fragment\" \/&gt;\r\n\r\n&lt;\/FrameLayout&gt;<\/pre>\n<p><b>CallsFragemnt.kt<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.example.techvidvanfragment\r\n\r\nimport androidx.fragment.app.Fragment\r\nimport androidx.fragment.app.FragmentManager\r\nimport androidx.fragment.app.FragmentPagerAdapter\r\n\r\nclass ViewPagerAdapter(supportFragmentManager: FragmentManager):FragmentPagerAdapter(supportFragmentManager,\r\n    BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)\r\n{\r\n    private val fragment_list = ArrayList&lt;Fragment&gt;();\r\n    private val fragment_title = ArrayList&lt;String&gt;();\r\n\r\n    override fun getCount(): Int\r\n    {\r\n        return fragment_list.size;\r\n    }\r\n\r\n    override fun getItem(position: Int): Fragment {\r\n        return fragment_list[position];\r\n    }\r\n\r\n    override fun getPageTitle(position: Int): CharSequence? {\r\n        return fragment_title[position];\r\n    }\r\n\r\n    fun addFragementToPager(fragment: Fragment, title:String)\r\n    {\r\n        fragment_list.add(fragment);\r\n        fragment_title.add(title);\r\n    }\r\n\r\n}<\/pre>\n<p><strong>9: <\/strong>Now, you need to create a new kotlin class. Just select your package &#8212;&gt; Right-click &#8212;&gt; Click on New and Select Kotlin Class and enter the name as \u201cViewPagerAdapter.\u201dNow just copy the below code into ViewPagerAdapter.kt file.<\/p>\n<p><strong>ViewPagerAdapter.kt<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.example.techvidvanfragment\r\n\r\nimport androidx.fragment.app.Fragment\r\nimport androidx.fragment.app.FragmentManager\r\nimport androidx.fragment.app.FragmentPagerAdapter\r\n\r\nclass ViewPagerAdapter(supportFragmentManager: FragmentManager):FragmentPagerAdapter(supportFragmentManager,\r\n    BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)\r\n{\r\n    \/\/creating array to store the fragments\r\n    private val fragment_list = ArrayList&lt;Fragment&gt;();\r\n\r\n    \/\/this array will store their title\r\n    private val fragment_title = ArrayList&lt;String&gt;();\r\n\r\n    override fun getCount(): Int\r\n    {\r\n        \/\/returns the count of fragments\r\n        return fragment_list.size;\r\n    }\r\n\r\n    override fun getItem(position: Int): Fragment \r\n    {\r\n        \/\/ returns the fragment based on the position\r\n        \/\/ user selected\r\n        return fragment_list[position];\r\n    }\r\n\r\n    override fun getPageTitle(position: Int): CharSequence? \r\n    {\r\n        \/\/ returns the fragment title of the fragment\r\n        return fragment_title[position];\r\n    }\r\n\r\n    fun addFragementToPager(fragment: Fragment, title:String)\r\n    {\r\n        \/\/function to add fragments in array\r\n        fragment_list.add(fragment);\r\n        fragment_title.add(title);\r\n    }\r\n\r\n}\r\n<\/pre>\n<p><strong>10:<\/strong> <span style=\"font-weight: 400;\">Now, come to your Main Activity file and paste the below code there.<\/span><\/p>\n<p><strong>MainActivity.kt<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.example.techvidvanfragment\r\n\r\nimport androidx.appcompat.app.AppCompatActivity\r\nimport android.os.Bundle\r\nimport androidx.viewpager.widget.ViewPager\r\nimport com.google.android.material.tabs.TabLayout\r\n\r\nclass MainActivity : AppCompatActivity()\r\n{\r\n    \/\/declaring view pager\r\n    \/\/and tab layout\r\n    lateinit var pager:ViewPager;\r\n    lateinit var tabLayout:TabLayout;\r\n\r\n    override fun onCreate(savedInstanceState: Bundle?)\r\n    {\r\n        super.onCreate(savedInstanceState)\r\n        setContentView(R.layout.activity_main)\r\n\r\n        val adapter = ViewPagerAdapter(supportFragmentManager)\r\n\r\n        \/\/Setting up the fragements and the title using the\r\n        \/\/adapter class\r\n        adapter.addFragementToPager(ChatsFragment(), \"Chats\")\r\n        adapter.addFragementToPager(StatusFragment(), \"Status\")\r\n        adapter.addFragementToPager(CallsFragment(), \"Calls\")\r\n\r\n        \/\/setting up the adapter\r\n        \/\/to our view pager\r\n        pager = findViewById(R.id.view_pager);\r\n        pager.adapter = adapter;\r\n\r\n        \/\/Setting up the tabs with\r\n        \/\/the view pager\r\n        tabLayout = findViewById(R.id.tabs);\r\n        tabLayout.setupWithViewPager(pager);\r\n\r\n    }\r\n}\r\n<\/pre>\n<p><span style=\"font-weight: 400;\">So, now you can run your application and see the output.\u00a0<\/span><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Output_App_1.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81674\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Output_App_1.jpg\" alt=\"Android Fragment\" width=\"1080\" height=\"2280\" \/><\/a><\/p>\n<p><span style=\"font-weight: 400;\">You can find three tabs: Chats, Status, and Fragments.\u00a0<\/span><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Output_App_2.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81675\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Output_App_2.jpg\" alt=\"Android Chat Fragment\" width=\"1080\" height=\"2280\" \/><\/a><\/p>\n<p><span style=\"font-weight: 400;\">When you swipe right or left, to then your fragments will be changed.\u00a0<\/span><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Output_App_3.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81676\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Output_App_3.jpg\" alt=\"Android Calls Fragment\" width=\"1080\" height=\"2280\" \/><\/a><\/p>\n<h2>Summary<\/h2>\n<p><span style=\"font-weight: 400;\">Through this article, you understood what a fragment is and the need to use a fragment. You came across the various types of fragments and understood how fragments interact with the activity. Moving further, you went across the lifecycle of a fragment and the different callback methods. <\/span><\/p>\n<p><span style=\"font-weight: 400;\">Finally, you saw how you could implement fragments in your projects. I hope you are enjoying the course so on and are getting to know many new things.\u00a0\u00a0<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This article will help you understand what fragments are and the several types of fragments in android. You will also know how to create a fragment and communicate between the fragments and the activities.&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":81665,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2791],"tags":[3711,3712,3713,3714,3715],"class_list":["post-81420","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android","tag-android-fragment-and-communication","tag-android-fragments","tag-android-fragments-with-activity","tag-lifecycle-of-android-fragments","tag-methods-of-android-fragments"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Android Fragments - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn what is fragment in Android, its need &amp; several types of Android fragment. See how fragments interact with activity in various devices\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/android-fragments\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Android Fragments - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn what is fragment in Android, its need &amp; several types of Android fragment. See how fragments interact with activity in various devices\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/android-fragments\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-02T03:30:29+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-08-02T15:43:41+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Android_Fragments.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Android Fragments - TechVidvan","description":"Learn what is fragment in Android, its need & several types of Android fragment. See how fragments interact with activity in various devices","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/","og_locale":"en_US","og_type":"article","og_title":"Android Fragments - TechVidvan","og_description":"Learn what is fragment in Android, its need & several types of Android fragment. See how fragments interact with activity in various devices","og_url":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-07-02T03:30:29+00:00","article_modified_time":"2024-08-02T15:43:41+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Android_Fragments.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Android Fragments","datePublished":"2021-07-02T03:30:29+00:00","dateModified":"2024-08-02T15:43:41+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/"},"wordCount":2011,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Android_Fragments.jpg","keywords":["Android Fragment and communication","Android Fragments","Android Fragments with Activity","Lifecycle of Android Fragments","Methods of Android Fragments"],"articleSection":["Android Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/android-fragments\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/","url":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/","name":"Android Fragments - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Android_Fragments.jpg","datePublished":"2021-07-02T03:30:29+00:00","dateModified":"2024-08-02T15:43:41+00:00","description":"Learn what is fragment in Android, its need & several types of Android fragment. See how fragments interact with activity in various devices","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/android-fragments\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Android_Fragments.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Android_Fragments.jpg","width":1200,"height":628,"caption":"Android Fragments"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/android-fragments\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Android Fragments"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81420","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=81420"}],"version-history":[{"count":2,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81420\/revisions"}],"predecessor-version":[{"id":447562,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81420\/revisions\/447562"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/81665"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=81420"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=81420"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=81420"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}