Fragments represent reusable behaviors or portions of the user interface in an Android app.
A
Fragment
represents a behavior or a portion of user interface in anActivity
. and reuse a fragment in multiple activities.Fragments were first introduced in Android 3.0 (API 11). However, the Support V4 Library back-ported fragments to every version of Android from 1.6 (API 4) onwards.
Here are the important things to understand about fragments:
- A Fragment is a combination of an XML layout file and a java class much like an Activity.
- Using the support library, fragments are supported back to all relevant Android versions.
- Fragments encapsulate views and logic so that it is easier to reuse within activities.
- Fragments are standalone components that can contain views, events and logic.
- You can combine multiple fragments in a single activity to build a multi-pane UI.
- You can add fragments to your app directly with XML or through the
FragmentManager
in Java. - The
FragmentManager
is responsible for all runtime management of fragments including adding, removing, hiding, showing, or otherwise navigating between fragments. The fragment manager is also responsible for finding fragments within an activity.
The ApiDemos sample application present in the SDK provides runnable fragment examples and source code.
You can find more information in:
- Android Developers Guide on Fragments
- Developer Blog: The Android 3.0 Fragments API
- Official Fragment Documentation
- Official Support v4 Fragment Documentation
- Creating and Using Fragments - Codepath
- Compatibility Library's official documentation
Tag Usage:
android android-fragmentmanager android-fragmentactivity android-listfragment android-dialogfragment fragmentpageradapter fragment-tab-host fragmenttransaction fragmentstatepageradapter android-nested-fragment dialogfragment fragment-backstack