1. Welcome
In this codelab, you learn about fragments, which represent a behavior or a portion of the user interface in an activity. You will create a fragment inside a fun starter app called AndroidTrivia. In the next codelab, you learn more about navigation and do further work on the AndroidTrivia app.
What you should already know
- The fundamentals of Kotlin
- How to create basic Android apps in Kotlin
- How to work with layouts
What you'll learn
- How to add a Fragment statically to your app
What you'll do
- Create a Fragment inside an activity.
2. App overview
In the three codelabs that make up this lesson, you work on an app called AndroidTrivia. The completed app is a game in which the user answers three trivia questions about Android coding. If the user answers all three questions correctly, they win the game and can share their results.
The AndroidTrivia app illustrates navigation patterns and controls. The app has several components:
- In the title screen, shown on the left in the screenshot above, the user starts the game.
- In the game screen with questions, shown in the middle above, the user plays the game and submits their answers.
- The navigation drawer, shown on the right above, slides out from the side of the app and contains a menu with a header. The drawer icon
opens the navigation drawer. The navigation-drawer menu contains a link to the About page and a link to the rules of the game.
The top of the app displays a view called the app bar (or action bar) which shows the app's name.
3. Task: Explore the starter app project
In this codelab, you work from a starter app that provides template code and Fragment classes that you need as you complete the Trivia app.
- Download the AndroidTrivia-Starter Android Studio project. You may have to download the entire android-kotlin-fundamentals-starter-apps zip file.
- Open the project in Android Studio and run the app. When the app opens, it doesn't do anything other than display the app name and a blank screen.
- In the Android Studio Project pane, open the Project: Android view to explore the project files. Open the app > java folder to see the
MainActivity
class and Fragment classes.
- Open the res > layout folder and double-click activity_main.xml. The
activity_main.xml
file appears in the Layout Editor. - Open the Design tab. The Component Tree for the
activity_main.xml
file shows the root layout as verticalLinearLayout
.
In a vertical linear layout, all the child views in the layout are aligned vertically.
4. Task: Add a fragment
A Fragment
represents a behavior or a portion of user interface (UI) in an Activity
. You can combine multiple fragments in a single activity to build a multi-pane UI, and you can reuse a Fragment
in multiple activities.
Think of a Fragment
as a modular section of an activity, something like a "sub-activity" that you can also use in other activities:
- A
Fragment
has its own lifecycle and receives its own input events. - You can add or remove a
Fragment
while the activity is running. - A
Fragment
is defined in a Kotlin class. - A
Fragment
's UI is defined in an XML layout file.
The AndroidTrivia app has a main activity and several fragments. Most of the fragments and their layout files have been defined for you. In this task, you create a fragment and add the fragment to the app's main activity.
Step 1: Add a Fragment class
In this step, you create a blank TitleFragment
class. Start by creating a Kotlin class for a new Fragment:
- In Android Studio, click anywhere inside the Project pane to bring the focus back to the project files. For example, click the com.example.android.navigation folder.
- Select File > New > Fragment > Fragment (Blank).
- For the Fragment name, enter TitleFragment.
- For the Fragment layout name, enter placeholder_layout (we will not use this layout for our app as it already has the layout designed for TitleFragment).
- For source language, select Kotlin.
- Click Finish.
- Open the
TitleFragment.kt
fragment file, if it is not already open. It contains theonCreateView()
method, which is one of the methods that's called during a Fragment's lifecycle. - Delete the code inside
onCreateView()
. TheonCreateView()
function is left with only the following code:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
}
- In
TitleFragment
class, delete theonCreate()
method, the fragment initialization parameters and companion object. Make sure yourTitleFragment
class looks like the following:
class TitleFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
}
}
Create a binding object
The Fragment won't compile now. To make the Fragment compile, you need to create a binding object and inflate the Fragment's view (which is equivalent to using setContentView()
for an Activity).
- In the
onCreateView()
method inTitleFragment.kt
, create abinding
variable (val binding
). - To inflate the Fragment's view, call the
DataBindingUtil.inflate()
method on the Fragment'sBinding
object, which isFragmentTitleBinding
.
Pass four arguments into the DataBindingUtil.inflate
method:
inflater
, which is theLayoutInflater
used to inflate the binding layout.- The XML layout resource of the layout to inflate. Use one of the layouts that is already defined for you,
R.layout.fragment_title
. container
for the parentViewGroup
. (This parameter is optional.)false
for theattachToParent
value.
- Assign the binding that
DataBindingUtil.inflate
returns to thebinding
variable. - Return
binding.root
from the method, which contains the inflated view. YouronCreateView()
method now looks like the following code:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding = DataBindingUtil.inflate<FragmentTitleBinding>(inflater,
R.layout.fragment_title,container,false)
return binding.root
}
- Open res>layout and delete
placeholder_layout.xml
.
Step 2: Add the new fragment to the main layout file
In this step, you add the TitleFragment
to the app's activity_main.xml
layout file.
- Open res > layout > activity_main.xml and select the Code tab to view the layout XML code.
- Inside the existing
LinearLayout
element, add afragment
element. - Set the fragment's ID to
titleFragment
. - Set the fragment's name to the full path of the Fragment class, which in this case is
com.example.android.navigation.TitleFragment
. - Set the layout width and height to
match_parent
.
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/titleFragment"
android:name="com.example.android.navigation.TitleFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
</layout>
- Run the app. The Fragment has been added to your main screen.
5. Solution code
Android Studio project: AndroidTriviaFragment
Alert: Make sure to use the latest version of Fragment (androidx.fragment.app.Fragment). The older versions of Fragment were deprecated in API level 28.
6. Summary
In this codelab, you added a Fragment to the AndroidTrivia app, which you will keep working on in the next two codelabs in this lesson.
- A Fragment is a modular section of an activity.
- A Fragment has its own lifecycle and receives its own input events.
- Use the
<fragment>
tag to define the layout for the Fragment in the XML layout file. - Inflate the layout for a Fragment in
onCreateView()
. - You can add or remove a Fragment while the activity is running.
7. Learn more
Udacity course:
Android developer documentation:
8. Homework
This section lists possible homework assignments for students who are working through this codelab as part of a course led by an instructor. It's up to the instructor to do the following:
- Assign homework if required.
- Communicate to students how to submit homework assignments.
- Grade the homework assignments.
Instructors can use these suggestions as little or as much as they want, and should feel free to assign any other homework they feel is appropriate.
If you're working through this codelab on your own, feel free to use these homework assignments to test your knowledge.
Answer these questions
Question 1
What are some of the differences between fragments and activities? Select all the statements that are true.
- When creating a Fragment, you inflate the layout in the
onCreateView()
method. When creating an Activity, you inflate the layout inonCreate()
. - An Activity has its own layout, but a Fragment cannot have its own layout.
- An Activity has its own lifecycle, but a Fragment doesn't.
- When inflating the layout for either a Fragment or an Activity, you can reference the layout as
R.layout.
layoutname
.
Question 2
Which of the following statements about fragments are true? Select all that apply.
- You can use a Fragment in more than one Activity.
- One Activity can have multiple fragments.
- After you define a Fragment in a Kotlin class, the Fragment is automatically added to the
activity_main.xml
layout file. - Use the
<fragment>
tag to define the place in a layout file where a Fragment is to be inserted.
9. Next codelab
For links to other codelabs in this course, see the Android Kotlin Fundamentals codelabs landing page.