Fragments

A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events.

You can consider a fragment as lightweight version of an activity.

Typical example - on small screen app can show fragment with list. When the user clicks on a list item app will replace this fragment by fragment that show details. On larger screen app can show both fragments at the same time: list on the left and details of the current list item on the right.

Add dependency to include the AndroidX Fragment library.

Add dependency
val fragment_version = "1.3.4"

// Java language implementation
implementation("androidx.fragment:fragment:$fragment_version")
// Kotlin
implementation("androidx.fragment:fragment-ktx:$fragment_version")

To create a fragment, extend the AndroidX Fragment class, and override its methods to insert your app logic, similar to the way you would create an Activity class.

The arguments Bundle can then be retrieved from within your fragment by calling requireArguments(), and the appropriate Bundle getter methods can be used to retrieve each argument.

Create fragment example
class ExampleFragment : Fragment(R.layout.example_fragment) {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val someInt = requireArguments().getInt("some_int")
        // ...
    }
    
    // ...
}

Fragments are hosted by an activity or another fragment. The fragment’s view hierarchy becomes part of the host’s view hierarchy.

FragmentContainerView is extension of FrameLayout designed specifically for Fragments. Add it to the layout of activity or parent fragment in place where you want display fragment.

FragmentContainerView example
<!--  res/layout/example_activity.xml -->
<androidx.fragment.app.FragmentContainerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

FragmentManager class is responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the fragment backstack (read more how to manage fragments)

Add root fragment
class ExampleActivity : AppCompatActivity(R.layout.example_activity) {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // set our fragment as root fragment at first time  
        if (savedInstanceState == null) {

            val bundle = bundleOf("some_int" to 0)
            
            supportFragmentManager.commit {
                setReorderingAllowed(true) // You should always use it in transaction
                add<ExampleFragment>(R.id.fragment_container_view, args = bundle)
            }
        }
    }
}

Also you can add fragment in the layout.xml file via FragmentContainerView or <fragment> element.

<!-- res/layout/example_activity.xml -->
<androidx.fragment.app.FragmentContainerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.example.ExampleFragment" />

<!-- not recommended, but you can meet it in old code --> <fragment android:id="@+id/cat_fragment" android:name="com.example.ExampleFragment" android:layout_width="match_parent" android:layout_height="match_parent" />

life cycle

method description
onCreate(savedInstanceState)

Called to do initial creation of a fragment. This is called after onAttach() and before onCreateView().

Note that this can be called while the fragment's activity is still in the process of being created.

onCreateView(inflater, container, savedInstanceState)

Override to create view of fragment. It is recommended to only inflate the layout in this method and move logic that operates on the returned View to onViewCreated(). Non-graphical fragments can return null. This will be called between onCreate() and onViewCreated().

A default View can be returned by calling Fragment(int) in your constructor. Otherwise, this method returns null.

onViewCreated(view, savedInstanceState) Called immediately after onCreateView() has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.
onViewStateRestored (savedInstanceState) Called when all saved state has been restored into the view hierarchy of the fragment. This can be used to do initialization based on saved state that you are letting the view hierarchy track itself, such as whether check box widgets are currently checked. This is called after onViewCreated() and before onStart().
onStart() Called when the Fragment is visible to the user.
onResume() Called when the fragment is visible to the user and actively running.
onPause() Called when the Fragment is no longer resumed.
onStop() Called when the Fragment is no longer started.
onSaveInstanceState (outState) Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. If a new instance of the fragment later needs to be created, the data you place in the Bundle here will be available in the Bundle given to onCreate( ), onCreateView(), and onViewCreated().
onDestroyView () Called when the view has been detached from the fragment.
onDestroy () Called when the fragment is no longer in use. This is called after onStop() and before onDetach().