Creating and Using Fragments

Introduction

A Fragment is a reusable portion of an activity. It typically defines a part of the user interface intended to be used across activities.

Fragments must be used as a part of Android activities and can’t be used independently.

Similar to a View, a Fragment binds a layout to a class, but unlike a View, it provides us with an abstraction of several lifecycle methods. A Fragment can contain views, events, and logics to manage the interaction of views and events.

Importance of fragments

  • A Fragment allows us to reuse the binding of a View and its behavior based on the events it supports across activities.
  • It allows device-specific support (phone or tablet) or orientation (landscape or portrait) UIs to reuse shared elements while being open to differences.
  • In an application that follows the fragment-based architecture, activities serve merely as navigation controllers while fragments are responsible for rendering views and the relevant logic.

Creating a fragment

Let’s discuss the steps to create and use a fragment in our ExampleActivity.

Environment setup

Add the following dependency in the app/build.gradle file to use the AndroidX Fragment class.

implementation("androidx.fragment:fragment-ktx:1.4.0")

Make sure that Google’s Maven repository is configured for our app.

Get hands-on with 1200+ tech skills courses.