Runoob Tutorial ArchiveEnglish

Android Fragment

Android Fragment

A Fragment is a part of an Activity, making the Activity design more modular. We can consider a Fragment as a sub-Activity.

Here are some important knowledge points about Fragments -

Fragments are created by inheriting the Fragment class. Fragments can be inserted into your activity by declaring them in the layout file of the activity usingelements.

Before the introduction of Fragments, we had a limitation because at any given point in time, only a single activity could be displayed on the screen. We could not split the device screen and have independent controls for different parts. With the introduction of Fragments, we gained greater flexibility, and the restriction that only a single activity can be on the screen at any given time was removed. Now we can have a single activity, but each activity is composed of multiple Fragments, and each Fragment has its own layout, events, and complete lifecycle.

Below is a typical example demonstrating how two UI modules defined by Fragments can be combined in an activity designed for a tablet and separated in an activity designed for a handheld device.

Image

When running on a tablet-sized device, this application can embed two Fragments in Activity A. On a mobile device screen, due to insufficient space, Activity A only contains a Fragment with an article list. When the user clicks an article, Activity B, which contains the second Fragment, is launched to read the article.


Fragment Lifecycle

Android Fragments have their own lifecycle, which is similar to Android Activities. Below is a simple introduction to the different stages of its lifecycle.

Image

This is a list of methods you can override in the Fragment class:


How to use fragments?

This introduces the simple steps to create a fragment.


Fragment Types

Basic fragments can be divided into the following three types: