To illustrate examples of fragments and the back stack, we will extend our application further. We will create a fragment to display a user manual containing the text, Lorem ipsum. First we need to create a new fragment. Create a new layout named fragment_manual. Update the layout as shown in this example:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10dp" android:text="@string/lorem_ipsum_sit_dolore" android:textSize="14sp" /> </LinearLayout>
This is a simple layout containing the text view stretched across the whole parent view. The fragment that will use this layout will be called ManualFragment. Create a class for the fragment and make sure it has the following content:
package com.journaler.fragment import com.journaler.R class ManualFragment : BaseFragment() { override val logTag = "Manual Fragment" override fun getLayout() = R.layout.fragment_manual }
Finally, let's add it to the fragment back stack. Update the onCreate() method of MainActivity as follows:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val fragment = ItemsFragment() supportFragmentManager .beginTransaction() .add(R.id.fragment_container, fragment) .commit() filter_menu.setText("H") filter_menu.setOnClickListener { val userManualFrg = ManualFragment() supportFragmentManager .beginTransaction() .replace(R.id.fragment_container, userManualFrg) .addToBackStack("User manual") .commit() } }
Build and run the application. The top-right header button will have label H; click on it. The fragment containing the Lorem ipsum text fills the view. Tap on the back button and the fragment disappears. This means that you successfully added and removed the fragment from the back stack.
We have to try one more thing--click on the same button two to three times in the row. Click on the back button. Then again. And again. You will go through the back stack until you reach the first fragment. If you tap on the back button once more, you will leave the application. Observe your Logcat.
Do you remember the order in which lifecycle methods are executed? You can recognize that each time a new fragment is added to the top, the one below pauses. When we start going back by pressing the back button, the fragment on the top pauses and the one below resumes. Fragments that are removed from the back stack enter the onDestroy() method at the end.