0% found this document useful (0 votes)
31 views

Create A Fragment - Android Developers

Uploaded by

Jeebers Crrebers
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Create A Fragment - Android Developers

Uploaded by

Jeebers Crrebers
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Create a fragment | Android Developers https://developer.android.

com/guide/fragments/create

A fragment (/guide/fragments) represents a modular po�ion of the user inte�ace within an


activity. A fragment has its own lifecycle, receives its own input events, and you can add
or remove fragments while the containing activity is running.

This document describes how to create a fragment and include it in an activity.

Fragments require a dependency on the AndroidX Fragment library


(/jetpack/androidx/releases/fragment). You need to add the Google Maven repository
(/studio/build/dependencies#google-maven) to your project's �le in order to
include this dependency.

(#groovy)
(#kotlin)

dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
...
}
}

To include the AndroidX Fragment library to your project, add the following dependencies
in your app's �le:

(#groovy)
(#kotlin)

dependencies {
val fragment_version = "1.8.5"

∕∕ Java language implementation


implementation("androidx.fragment:fragment:$fragment_version")
∕∕ Kotlin

1 of 6 11/16/24, 08:58
Create a fragment | Android Developers https://developer.android.com/guide/fragments/create

implementation("androidx.fragment:fragment-ktx:$fragment_version")
}

To create a fragment, extend the AndroidX


(/reference/androidx/fragment/app/Fragment) class, and override its methods to inse� your
app logic, similar to the way you would create an (/reference/android/app/Activity)
class. To create a minimal fragment that de�nes its own layout, provide your fragment's
layout resource to the base constructor, as shown in the following example:

(#java)
(#kotlin)

class ExampleFragment : Fragment(R.layout.example_fragment)

The Fragment library also provides more specialized fragment base classes:

(/reference/androidx/fragment/app/DialogFragment)

Displays a �oating dialog. Using this class to create a dialog is a good alternative to
using the dialog helper methods in the (/reference/android/app/Activity) class,
as fragments automatically handle the creation and cleanup of the . See
Displaying dialogs with (/guide/fragments/dialogs) for more details.

(/reference/androidx/preference/PreferenceFragmentCompat)

Displays a hierarchy of (/reference/androidx/preference/Preference) objects


as a list. You can use to create a se�ings screen
(/develop/ui/views/components/se�ings) for your app.

Generally, your fragment must be embedded within an AndroidX


(/reference/androidx/fragment/app/FragmentActivity) to contribute a po�ion of UI to that
activity's layout. is the base class for
(/reference/androidx/appcompat/app/AppCompatActivity), so if you're already subclassing

2 of 6 11/16/24, 08:58
Create a fragment | Android Developers https://developer.android.com/guide/fragments/create

to provide backward compatibility in your app, then you do not need


to change your activity base class.

You can add your fragment to the activity's view hierarchy either by de�ning the fragment
in your activity's layout �le or by de�ning a fragment container in your activity's layout �le
and then programmatically adding the fragment from within your activity. In either case,
you need to add a
(/reference/androidx/fragment/app/FragmentContainerView) that de�nes the location where the
fragment should be placed within the activity's view hierarchy. It is strongly
recommended to always use a as the container for fragments,
as includes �xes speci�c to fragments that other view groups
such as do not provide.

To declaratively add a fragment to your activity layout's XML, use a


element.

Here's an example activity layout containing a single :

<!-- res∕layout∕example_activity.xml -->


<androidx.fragment.app.FragmentContainerView
xmlns:android="http:∕∕schemas.android.com∕apk∕res∕android"
android:id="@+id∕fragment_container_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.ExampleFragment" ∕>

The a�ribute speci�es the class name of the to instantiate.


When the activity's layout is in�ated, the speci�ed fragment is instantiated,
(/reference/androidx/fragment/app/Fragment#onIn�ate(android.content.Context,
%2520android.util.A�ributeSet,%2520android.os.Bundle))
is called on the newly instantiated fragment, and a is created to
add the fragment to the .

Note: You can use the a�ribute instead of as an alternative way to specify which
to instantiate.

3 of 6 11/16/24, 08:58
Create a fragment | Android Developers https://developer.android.com/guide/fragments/create

To programmatically add a fragment to your activity's layout, the layout should include a
to serve as a fragment container, as shown in the following
example:

<!-- res∕layout∕example_activity.xml -->


<androidx.fragment.app.FragmentContainerView
xmlns:android="http:∕∕schemas.android.com∕apk∕res∕android"
android:id="@+id∕fragment_container_view"
android:layout_width="match_parent"
android:layout_height="match_parent" ∕>

Unlike the XML approach, the a�ribute isn't used on the


here, so no speci�c fragment is automatically instantiated.
Instead, a (/reference/androidx/fragment/app/FragmentTransaction) is
used to instantiate a fragment and add it to the activity's layout.

While your activity is running, you can make fragment transactions such as adding,
removing, or replacing a fragment. In your , you can get an instance of
the (/reference/androidx/fragment/app/FragmentManager), which can be
used to create a . Then, you can instantiate your fragment within
your activity's method using
(/reference/androidx/fragment/app/FragmentTransaction#add(int,%20java.lang.Class%3C?
%20extends%20androidx.fragment.app.Fragment%3E,%20android.os.Bundle))
, passing in the ID of the container in your layout and the fragment class you
want to add and then commit the transaction, as shown in the following example:

(#java)
(#kotlin)

class ExampleActivity : AppCompatActivity(R.layout.example_activity) {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
supportFragmentManager.commit {
setReorderingAllowed(true)
add<ExampleFragment>(R.id.fragment_container_view)
}
}
}

4 of 6 11/16/24, 08:58
Create a fragment | Android Developers https://developer.android.com/guide/fragments/create

Note: You should always use when pe�orming a


. For more information on reordered transactions, see Fragment transactions
(/guide/fragments/transactions#reordering).

In the previous example, note that the fragment transaction is only created when
is . This is to ensure that the fragment is added only once,
when the activity is �rst created. When a con�guration change occurs and the activity is
recreated, is no longer , and the fragment does not need to be
added a second time, as the fragment is automatically restored from the
.

If your fragment requires some initial data, arguments can be passed to your fragment by
providing a (h�ps://developer.android.com/reference/android/os/Bundle) in the call to
, as shown below:

(#java)
(#kotlin)

The arguments can then be retrieved from within your fragment by calling
(/reference/androidx/fragment/app/Fragment#requireArguments()), and the
appropriate ge�er methods can be used to retrieve each argument.

(#kotlin)
(#java)

5 of 6 11/16/24, 08:58
Create a fragment | Android Developers https://developer.android.com/guide/fragments/create

Fragment transactions and the are covered in more detail in the


Fragment manager guide (/guide/fragments/fragmentmanager).

Content and code samples on this page are subject to the licenses described in the Content License
(/license). Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its a�liates.

Last updated 2024-10-30 UTC.

6 of 6 11/16/24, 08:58

You might also like