Android Fragments Tutorial: An Introduction with Kotlin

In this Android Fragments with Kotlin tutorial you will learn the fundamental concepts of fragments while creating an app that displays dogs breeds. By Aaqib Hussain.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Navigating the Fragment Back Stack

The fragment back stack is not independent of the activity back stack. Think of it as an extra stack of history on top of that of the host activity.

Fragments and back stack

When you navigate between activities, each one gets placed on the activity back stack. Whenever you commit a FragmentTransaction, you have the option to add that transaction to the back stack.

So, what does addToBackStack() do? It adds the replace() to the back stack so that when the user hits the device’s back button it undoes the transaction. In this case, hitting the back button sends the user back to the full list.

The add() transaction for the list omits calling addToBackStack(). This means that the transaction is part of the same history entry as the entire activity. If the user hits the back button from the list, it backs the user out of the app.

Now, build and run and you should see details about each breed when you tap on them:

Screenshot with breed details

With that you’re done! You now have an app El Dogo that displays details about the dogs breeds.

Where To Go From Here?

You can find the Final Project for this tutorial by clicking the Download Materials button at the top or bottom of this tutorial.

There is a lot more to learn and do with fragments. Like any kind of tool or feature, consider whether fragments fit your app’s needs and, if they do, try to follow best practices and conventions.

To take your skills to the next level, here are some additional things to explore:

.

  • Use fragments within a ViewPager. Many apps, including the Play Store, utilize a swipeable, tabbed content structure via ViewPagers. You can learn more in our ViewPager tutorial
  • Use a more powerful, advantageous DialogFragment instead of a plain vanilla dialog or AlertDialog.
  • Play with how fragments interact with other parts of an Activity, like the app bar.
  • Create adaptive UIs with fragments. In fact, you should run through Adaptive UI in Android Tutorial.
  • Use fragments as part of the implementation of a high-level behavioral architecture. You can take a look at Common Design Patterns for Android as a good starting point to get the architecture ball rolling.
  • To learn more about Data Binding check this reference.

We hope that you’ve enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!