Notes: 01. Work with Touch States
Prerequisites for this course are Android Studio 4, Kotlin 1.4 and either a physical device that can run Android 5 (API 21) or above, or an emulator with the same support. This tutorial assumes you have basic knowledge of Kotlin and Android. If you’re new to Android, check out our Android learning paths.
The app has a single screen. There are three cards aligned vertically, one for each of the fruits: banana, orange and lime. Each displays an image beside the name of the fruit and the quantity added. The fourth card is actually a button that contains the words “Mystery fruit”. Later, you’ll learn how to display a dialog with an extra fruit item when the user taps this button.
Underneath the cards are three buttons. Initially, these buttons don’t do anything, but throughout this tutorial, you’ll add the following functionality to them.
Tapping Add fruit displays a dialog for adding fruit. The quantity amount is updated on the corresponding fruit card, and a Snackbar confirms which fruit was added and gives the user the option to undo if they picked the wrong fruit by accident.
Tapping Copy list saves a list of the fruits and their quantities to the clipboard on the device. A Toast gives confirmation feedback to the user.
Tapping Clear list resets all the fruit quantities to zero. Because this is an irreversible action, a dialog prompts the user to confirm they’re happy to proceed.
That might sound like a lot to fit into one screen, but each of these dialogs and notifications appears only temporarily. They take up a small area of the screen, yet their effect is mighty!
Often when you press a physical button, you feel it move with the force of your finger and hear a click when it catches on. These are little reassurances that the button has been fully pressed and is working as expected. When making a digital product, you need to make considerations for providing the same kind of feedback.
In Android, the standard way to do this is to provide a touch state on anything the user can interact with. This means that while the user is touching the button, the app confirms it has registered the touch by changing the background color. When the user releases their finger, the color returns to normal, or sometimes a ripple effect is produced. Keep in mind that touch states come pre-built into Material Components.
In your project, open the app package, resources, layout, activity_main.xml and take look at the MaterialCardView
attributes.
The card with ID card_mystery
has two extra attributes defined: clickable
and focusable
. This tells the component that the card will handle clicks, so the touch state is automatically added.