Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

41. An Android Jetpack Navigation Component Tutorial

The previous chapter described the Android Jetpack Navigation Component and how it integrates with the navigation graphing features of Android Studio to provide an easy way to implement navigation between the screens of an Android app. In this chapter a new Android Studio project will be created that makes use of these navigation features to implement an example app containing multiple screens. In addition to demonstrating the use of the Android Studio navigation graph editor, the example project will also implement the passing of data between origin and destination screens using type-safe arguments.

41.1 Creating the NavigationDemo Project

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Fragment + ViewModel template before clicking on the Next button.

Enter NavigationDemo into the Name field and specify com.ebookfrenzy.navigationdemo as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java.

41.2 Adding Navigation to the Build Configuration

A new Android Studio project does not, by default, include the Navigation component libraries in the build configuration files. Before performing any other tasks, therefore, the first step is to modify the app level build.gradle file. Locate this file in the project tool window (Gradle Scripts -> build.gradle (Module: NavigationDemo.app)), double-click on it to load it into the code editor and modify the dependencies section to add the navigation libraries:

.

.

dependencies {

    implementation 'androidx.navigation:navigation-fragment:2.3.0'

    implementation 'androidx.navigation:navigation-ui:2.3.0'

.

.

}

Note that newer versions of these libraries may have been released since this book was published. To identify and use newer versions of the libraries, add the above lines to the build file and then open the Project Structure dialog (File ->...

41.3 Creating the Navigation Graph Resource File

With the navigation libraries added to the build configuration the navigation graph resource file can now be added to the project. As outlined in “An Overview of the Navigation Architecture Component”, this is an XML file that contains the fragments and activities through which the user will be able to navigate, together with the actions to perform the transitions and any data to be passed between destinations.

Within the Project tool window, locate the res folder (app -> res), right-click on it and select the New ->Android Resource File menu option:

Figure 41-2

After the menu item has been selected, the New Resource File dialog will appear. In this dialog, name the file navigation_graph and change the Resource type menu to Navigation as outlined in Figure 41-3 before clicking on the OK button to create the file.

Figure 41-3

After the navigation graph resource file has been added to the project...

41.4 Declaring a Navigation Host

For this project, the navigation host fragment will be contained within the user interface layout of the main activity. This means that the destination fragments within the navigation graph will appear in the content area of the main activity currently occupied by the main_fragment.xml layout. Locate the main activity layout file in the Project tool window (app -> res -> layout -> main_activity.xml) and load it into the layout editor tool.

With the layout editor in Design mode, drag a NavHostFragment element from the Containers section of the Palette and drop it onto the container area of the activity layout as indicated by the arrow in Figure 41-5:

Figure 41-5

From the resulting Navigation Graphs dialog, select the navigation_graph.xml file created in the previous section and click on the OK button.

With the newly added NavHostFragment instance selected in the layout, use the Attributes tool window to change the ID of the...

41.5 Adding Navigation Destinations

Remaining in the navigation graph it is now time to add the first destination. Since the project already has a fragment for the first screen (main_fragment.xml) this will be the first destination to be added to the graph. Click on the new destination button as shown in Figure 41-7 to select or create a destination:

Figure 41-7

Select main_fragment as the destination so that it appears within the navigation graph:

Figure 41-8

The home icon positioned above the destination node indicates that this is the start destination. This means that the destination will be the first displayed when the activity containing the NavHostFragment is created. To change the start destination to another destination, select that node in the graph and click on the home button located in the toolbar.

Review the XML content of the navigation graph by switching the editor to Code mode:

<?xml version="1.0" encoding="utf-8"?>...

41.6 Designing the Destination Fragment Layouts

Before adding actions to navigate between destinations now is a good time to add some user interface components to the two destination fragments in the graph. Begin by double-clicking on the mainFragment destination so that the main_fragment.xml file loads into the layout editor. Select and delete the current TextView widget, then drag and drop Button and Plain Text EditText widgets onto the layout so that it resembles that shown in Figure 41-10 below:

Figure 41-10

Once the views are correctly positioned, click on the Infer constraints button in the toolbar to add any missing constraints to the layout. Select the EditText view and use the Attributes tool window to delete the default “Name” text and to change the ID of the widget to userText.

Return to the navigation_graph.xml file and double-click on the secondFragment destination to load the fragment_second.xml file into the layout editor, then select and delete...

41.7 Adding an Action to the Navigation Graph

Now that the two destinations have been added to the graph and the corresponding user interface layouts designed, the project now needs a way for the user to navigate from the main fragment to the second fragment. This will be achieved by adding an action to the graph which can then be referenced from within the app code.

To establish an action connection with the main fragment as the origin and second fragment as the destination, open the navigation graph and hover the mouse pointer over the vertical center of the right-hand edge of the mainFragment destination so that a circle appears as highlighted in Figure 41-12:

Figure 41-12

Click within the circle and drag the resulting line to the secondFragment destination:

Figure 41-13

Release the line to establish the action connection between the origin and destination at which point the line will change into an arrow as shown in Figure 41-14:

Figure 41-14

An...

41.8 Implement the OnFragmentInteractionListener

Before adding code to trigger the action, the MainActivity class will need to be modified to implement the OnFragmentInteractionListener interface. This is an interface that was generated within the SecondFragment class when the blank fragment was created within the navigation graph editor. In order to conform to the interface, the activity needs to implement a single method named onFragmentInteraction() and is used to implement communication between the fragment and the activity.

Edit the MainActivity.java file and modify it so that it reads as follows:

.

.

import android.net.Uri;

.

.

public class MainActivity extends AppCompatActivity implements SecondFragment.OnFragmentInteractionListener {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

 ...

41.9 Triggering the Action

Now that the action has been added to the navigation graph, the next step is to add some code within the main fragment to trigger the action when the Button widget is clicked. Locate the MainFragment.java file, load it into the code editor and modify the onActivityCreated() method to obtain a reference to the button instance and to configure an onClickListener instance to be called when the user clicks the button:

.

.

import android.widget.Button;

import androidx.navigation.Navigation;

.

.

public class MainFragment extends Fragment {

.

.

    @Override

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

        mViewModel = new ViewModelProvider(this).get(MainViewModel.class);

 

      ...

41.10 Passing Data Using Safeargs

The next objective in this tutorial is to pass the text entered into the EditText view in the main fragment to the second fragment where it will be displayed on the TextView widget. As outlined in the previous chapter, the Android Navigation component supports two approaches to passing data. This chapter will make use of type safe argument passing.

The first step in using safeargs is to add the safeargs plugin to the Gradle build configuration. Using the Project tool window, locate and edit the project level build.gradle file (Gradle Scripts -> build.gradle (Project: NavigationDemo)) to add the plugin to the dependencies as follows (once again keeping in mind that a more recent version may now be available):

buildscript {

    

    repositories {

        google()

        jcenter()

    }

...

41.11 Summary

This chapter has provided a practical example of how to implement Android app navigation using the Navigation Architecture Component together with the Android Studio navigation graph editor. Topics covered included the creation of a navigation graph containing both existing and new destination fragments, the embedding of a navigation host fragment within an activity layout, writing code to trigger navigation events and the passing of arguments between destinations using the Gradle safeargs plugin.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth