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

46. Working with the Floating Action Button and Snackbar

One of the objectives of this chapter is to provide an overview of the concepts of material design. Originally introduced as part of Android 5.0, material design is a set of design guidelines that dictate how the Android user interface, and that of the apps running on Android, appear and behave.

As part of the implementation of the material design concepts, Google also introduced the Android Design Support Library. This library contains a number of different components that allow many of the key features of material design to be built into Android applications. Two of these components, the floating action button and Snackbar, will also be covered in this chapter prior to introducing many of the other components in subsequent chapters.

46.1 The Material Design

The overall appearance of the Android environment is defined by the principles of material design. Material design was created by the Android team at Google and dictates that the elements that make up the user interface of Android and the apps that run on it appear and behave in a certain way in terms of behavior, shadowing, animation and style. One of the tenets of the material design is that the elements of a user interface appear to have physical depth and a sense that items are constructed in layers of physical material. A button, for example, appears to be raised above the surface of the layout in which it resides through the use of shadowing effects. Pressing the button causes the button to flex and lift as though made of a thin material that ripples when released.

Material design also dictates the layout and behavior of many standard user interface elements. A key example is the way in which the app bar located at the top of the screen should appear...

46.2 The Design Library

Many of the building blocks needed to implement Android applications that adopt the principles of material design are contained within the Android Design Support Library. This library contains a collection of user interface components that can be included in Android applications to implement much of the look, feel and behavior of material design. Two of the components from this library, the floating action button and Snackbar, will be covered in this chapter, while others will be introduced in later chapters.

46.3 The Floating Action Button (FAB)

The floating action button is a button which appears to float above the surface of the user interface of an app and is generally used to promote the most common action within a user interface screen. A floating action button might, for example, be placed on a screen to allow the user to add an entry to a list of contacts or to send an email from within the app. Figure 46-1, for example, highlights the floating action button that allows the user to add a new contact within the standard Android Contacts app:

Figure 46-1

To conform with the material design guidelines, there are a number of rules that should be followed when using floating action buttons. Floating action buttons must be circular and can be either 56 x 56dp (Default) or 40 x 40dp (Mini) in size. The button should be positioned a minimum of 16dp from the edge of the screen on phones and 24dp on desktops and tablet devices. Regardless of the size, the button must contain an...

46.4 The Snackbar

The Snackbar component provides a way to present the user with information in the form of a panel that appears at the bottom of the screen as shown in Figure 46-2. Snackbar instances contain a brief text message and an optional action button which will perform a task when tapped by the user. Once displayed, a Snackbar will either timeout automatically or can be removed manually by the user via a swiping action. During the appearance of the Snackbar the app will continue to function and respond to user interactions in the normal manner.

Figure 46-2

In the remainder of this chapter an example application will be created that makes use of the basic features of the floating action button and Snackbar to add entries to a list of items.

46.5 Creating the Example Project

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

Enter FabExample into the Name field and specify com.ebookfrenzy.fabexample 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.

Reviewing the Project

Since the Basic Activity template was selected, the activity contains four layout files. The activity_main.xml file consists of a CoordinatorLayout manager containing entries for an app bar, a toolbar and a floating action button.

The content_main.xml file represents the layout of the content area of the activity and contains a NavHostFragment instance. This file is embedded into the activity_main.xml file via the following include directive:

<include layout="@layout/content_main" />...

46.6 Removing Navigation Features

As outlined in “A Guide to the Android Studio Layout Editor Tool”, the Basic Activity template contains multiple fragments and buttons to navigate from one fragment to the other. For the purposes of this tutorial, these features are unnecessary and will cause problems later if not removed. Before moving ahead with the tutorial, modify the project as follows:

1. Within the Project tool window, navigate to and double-click on the app -> res -> navigation -> nav_graph.xml file to load it into the navigation editor.

2. Within the editor, select the SecondFragment entry in the Component Tree panel and tap the keyboard delete key to remove it from the graph.

3. Locate and delete the SecondFragment.java (app -> java -> <package name> -> SecondFragment) and fragment_second.xml (app -> res -> layout -> fragment_second.xml) files.

4. Locate the FirstFragment.java file, double click on it to load it...

46.7 Changing the Floating Action Button

Since the objective of this example is to configure the floating action button to add entries to a list, the email icon currently displayed on the button needs to be changed to something more indicative of the action being performed. The icon that will be used for the button is named ic_add_entry.png and can be found in the project_icons folder of the sample code download available from the following URL:

https://www.ebookfrenzy.com/retail/androidstudio41/index.php

Locate this image in the file system navigator for your operating system and copy the image file. Right-click on the app -> res -> drawable entry in the Project tool window and select Paste from the menu to add the file to the folder:

Figure 46-5

Next, edit the activity_main.xml file and change the image source for the icon from @android:drawable/ic_dialog_email to @drawable/ic_add_entry as follows:

<com.google.android.material.floatingactionbutton.FloatingActionButton...

46.8 Adding the ListView to the Content Layout

The next step in this tutorial is to add the ListView instance to the fragment_first.xml file. The ListView class provides a way to display items in a list format and can be found in the Legacy section of the Layout Editor tool palette.

Load the fragment_first.xml file into the Layout Editor tool, select Design mode if necessary, and select and delete the default TextView and Button objects. Locate the ListView object in the Legacy category of the palette and, with autoconnect mode enabled, drag and drop it onto the center of the layout canvas. Select the ListView object and change the ID to listView within the Attributes tool window. The Layout Editor should have sized the ListView to fill the entire container but may not have applied any constraints. Click on the Infer Constraints button to add missing constraints at which point the layout should appear as illustrated in Figure 46-6:

Figure 46-6

With the ListView object...

46.9 Adding Items to the ListView

Each time the floating action button is tapped by the user, a new item will be added to the ListView in the form of the prevailing time and date. To achieve this, some changes need to be made to the MainActivity.java file.

Begin by implementing the onStart() method to obtain a reference to the ListView instance and to initialize an adapter instance to allow us to add items to the list in the form of an array:

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.widget.Toolbar;

import android.view.View;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.ArrayAdapter;

import android.widget.ListView;

 

import java.util.ArrayList;

 

public class MainActivity extends AppCompatActivity {

 ...

46.10 Adding an Action to the Snackbar

The final task in this project is to add an action to the Snackbar that allows the user to undo the most recent addition to the list. Edit the MainActivity.java file and modify the Snackbar creation code to add an action titled “Undo” configured with an onClickListener named undoOnClickListener:

fab.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View view) {

        addListItem();

        Snackbar.make(view, "Item added to list",

              Snackbar.LENGTH_LONG)

                .setAction("Undo", undoOnClickListener).show();

 

    }

});

Within the...

46.11 Summary

This chapter has provided a general overview of material design, the floating action button and Snackbar before working through an example project that makes use of these features.

Both the floating action button and the Snackbar are part of the material design approach to user interface implementation in Android. The floating action button provides a way to promote the most common action within a particular screen of an Android application. The Snackbar provides a way for an application to both present information to the user and also allow the user to take action upon it.

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