Android SDK: User Interaction

In this series we are learning about Android SDK development from scratch! In the last part, we created a basic user interface design with some typical Android elements. In this section, we'll incorporate user interaction with the interface elements into the app.


Introduction

In this tutorial, we will detect and respond to user clicks on the Button element that we previously added. This involves a little Java programming within our app's main Activity class. Don't worry if you don't have much experience with Java, just follow the steps below. We will look more at Java syntax in the next section, to make sure you know everything you need to about the language to carry out initial Android development tasks.

You can handle user interaction a few different ways with Android. We will look at two typical approaches to detect user clicks on buttons, both of which involve adding a little XML code as well as implementing some Java processing. On Android there are several different interactive UI elements that can receive various kinds of user input. Your handling of this input must be tailored to the UI item in question, but the overall process remains roughly the same. We will use a button to start exploring user interaction on Android, since it is among the most simple and commonly used elements.


1. User Interaction Basics

Before we get into the details, let's explain a few UI concepts for those who are new to app development. To make an app interactive, we want to detect user interaction with particular elements. As we saw last time, on Android these are Views, in this case they are Buttons. To do this, we need to "listen" for the user interacting with the View in question. Although Android primarily runs on touchscreen mobile devices, we still use some of the language developed for interaction on a computer. For example, you will see the term "click" used to mean either clicking with a mouse or touching/ tapping with the finger.

The user can interact with the app in many ways. They can tap, slide, and "long-press" items. When one of these occurs, this is called an "event". Therefore we want to set the app to listen for particular events occurring on particular UI items. In this case, we'll listen for clicks (or taps/ touches) on the Button.

We want to respond and listen for user events. To do this we will add code to the Java Activity class to listen and respond to the button clicks. This code executes whenever a click event occurs on the button. The same process applies to handling user interaction with any View type, although the method code varies for different event types (i.e. events other than clicks).


2. Identifying UI Elements

Step 1

In order to tell which View the user is interacting with, we need to identify each interactive View in the app. We only have one initially, but your future apps may have multiple types of interactive Views in them. To achieve this, we give any View we need to identify a unique ID attribute we can use throughout the app.

Open your main layout file in Eclipse and switch to the XML editing tab. Locate the code we added for the Button element. Add an ID to it using the following syntax:

You need ID attributes on many of the elements you use in Android layouts, since they allow you to identify Views uniquely. Notice the "@+id" syntax. This prompts the Android tools to create a new ID in the project resources "R.java" file, specifying a text string which must also be unique within the app, in this case "myButton". In other parts of the XML layout code and in other XML and Java files in the app, we will use this name to specify the Button View. Save your layout file.

Step 2

Open your app's main Activity file. We're going to add a little bit of Java code, but don't worry too much if your Java isn't up to scratch, just try to understand the basic process involved in handling user interaction. If you are new to Java, when you work through the next tutorial you can refer back to this one to understand it fully. We're going to create a variable in the class to refer to the Button View. At the top of the class declaration, after the opening line:

Add the variable declaration:

We declare the visibility (more details on this next time), the variable type, and the name. Eclipse may underline the "Button" text with the error message "Button cannot be resolved to a type". We are using the Button type provided by the Android platform, so we must import this into the class file. Hover your mouse over the "Button" text and Eclipse will prompt you with a list of suggestions. Select "Import 'Button' (android.widget)". This adds to the list of import statements you can expand and collapse near the top of the class file.

Import Prompt

Step 3

Now we can retrieve a reference to the Button View in the layout, storing this reference in the variable we created. In your Activity onCreate method, after the following line in which we set the layout:

Enter a new line to retrieve the Button as follows:

Inside the brackets for "findViewById()" type "R." - Eclipse will prompt you with a list of resource types. Choose "id".

ID Resource Prompt

Type another period "." - Eclipse will present a list of existing ID values. We have only added one so far. Select the ID name we gave the Button ("myButton") from the list.

ID Name Prompt

You'll use this procedure regularly when you need to refer to resources in your Java code. You should now have the following line:

This statement assigns the Button View reference to the new variable we created, identifying the View using its ID.


3. Listening for Events

Step 1

The Android system only detects events on Views when we ask it to. Therefore we need to assign a listener to the View. We can do this in a couple of different ways, but let's keep it to one of the simplest: having the Activity class itself listen and respond to clicks. At the top of the class, extend the opening declaration line as follows.

Eclipse will alert you to the "OnClickListener" type as before. Hover over the error and select an import as you did before, choose "Import 'OnClickListener' (android.view.View)". Here you can see how Eclipse helps you to manage the ingredients in your project. It now displays another error message telling us we have to implement a method. We'll resolve this next.

The "implements OnClickListener" code says that the Activity class is going to implement a particular interface. We will look at this practice in more detail next time - it essentially means that the class is going to provide functionality of a specific kind, in this case the functionality that allows us to handle clicks.

Step 2

Move back to the Activity onCreate method. After the line in which you assigned the Button View reference to the variable using its ID, add the following line:

This line instructs the app to listen for clicks on the Button. The "this" in the brackets specifies the object that handles the clicks. In this case, it is the running instance of the Activity class itself.


4. Responding to Events

Step 1

Now we can respond to the button clicks. After the class onCreate method closing bracket:

Add the following method outline:

Carry out the import process again, hovering over "View" and selecting "Import 'View' (android.view)". Since we instructed the class to listen for clicks on the button, when a click on it does occur, the content of this method will execute (the content, or "method body", will be placed between the opening and closing curly brackets). The "View v" is a parameter to the method, this means that the method receives a reference to the clicked View, so we can identify it.

Step 2

Inside the onClick method, we first need to check which View was clicked. We only have one setup for click listening, but the app may later handle clicks on multiple Views. In the method body, check to see if the passed View parameter is the button we have a reference to in the variable we created:

This is a conditional statement (a structure we will cover in more detail next time) that checks the clicked View ID against the one we have a variable for. If the content of this block executes, we know the button we setup listening for was clicked. All of this testing may seem unnecessary when we only have one interactive element, but as you can imagine, when you have more than one clickable element you need to determine which one was clicked when onClick executes.

Step 3

Inside the if conditional block in onClick we can now respond to the button click. The response depends on the purpose of the button in a real app, but in this case we are demonstrating the process. Add the following code:

Here we simply alter the text displayed on the button when it is clicked. Your onClick method should now appear as follows:

Below is the result on a virtual device after clicking the button. We'll cover running your apps on actual and virtual devices later on, so you can see the results in action!

Click Result on AVD

5. Alternatives & Options

Step 1

We demonstrated one way to handle button clicks on Android, but there are others. An alternative worth noting is to add the following attribute to your Button in the XML layout:

This specifies the name of a method to execute when the button is clicked. This method should be added to the Activity class displaying the layout. This removes the need for almost all of the code you added to the Activity class, including creating the Button variable, storing the View reference in it, implementing OnClickListener, and setting the class as click listener for the button. In this case, instead of adding the onClick method to the class, you can add the following (with equivalent code in it to produce the same effect):

While this may seem simpler, the process of retrieving references to layout elements in Java is worth getting to know as you'll find yourself doing so often. Also if your layout has multiple clickable items in it, you may prefer to handle all of the click events in one method, which you can do using the first approach outlined above.

There are other ways to handle clicks on Views beyond the two we have explored here, but these are the simplest, and are therefore advisable for your first projects.

Step 2

In this tutorial we worked through the basic process of handling button clicks on Android. The platform offers a range of other user event types for different Views, including long clicks, key presses, and touch events. See the Developer Guide for an overview of the possibilities you can try out in your future projects.


Conclusion

In this part, we explored the basic process to follow when you want to respond to user clicks on buttons in your Android UI. There is more to user interaction on Android than what we touched on here, but you should now have a grasp of the generic approach to handle the user input that many of your first projects will conform to. You can use what we learned in this section as a foundation to build your Android UI skills on. In the next tutorial, we will run through the most essential features of the Java language you need familiarity with in order to successfully learn Android development.

Tags:

Comments

Related Articles