Android SDK Getting Started Guide 3: User interaction

Source: Internet
Author: User
Tags unique id

In this tutorial, we will set up the button element that was previously added to enable detection and response to user clicks. To achieve this goal, we need to involve slightly Java programming content in the main activity class of the application. If you have less experience in Java development, there is no need to worry, just follow the steps to complete the study. We'll delve into Java syntax in the next article in this series to ensure that you understand the programming language knowledge necessary for your initial Android development tasks.

You can implement user interaction in many different ways in Android. We will learn two of the most typical processing scenarios, so that the application button to the user click on the sensor-two scenarios will use a little bit of XML code and Java implementation process. Android contains several different interactive UI elements that are sufficient to sense the various input actions from the user. The input operation must be handled in a way that matches the UI item, but the whole process is still roughly the same. We will start with a button to explore user interaction on the Android platform, as the button is undoubtedly the simplest and most commonly used interface element.

1. User Interaction Basics

Before I go further into the details, I'll start by explaining several UI concepts to my friends who have just come into contact with application development work. In order to achieve application interaction, we need to use specific elements to detect user interaction. A friend who has read the previous article must remember that there is a view in Android, and in today's example, the button is specifically referred to. To achieve interaction, we first need to "listen" to the user's actions. While Android operates primarily on mobile devices with touch screens, you can still use programming languages to handle interactive development on your computer. For example, referring to the "click" section later, we mean using the mouse to tap or touch/tap the corresponding position with your finger.

Users interact with the application in a variety of ways. They can touch, scrub, and "press and hold" the corresponding item. When these action activities occur, we call them an "event". Therefore, we need to set the application to listen for specific events on a particular UI item. In today's example, we need to listen to the click (or Touch/TAP) action on the button.

We need to listen and respond to this kind of user event. To do this, we'll add code to the Java activity class to listen and respond to button clicks. As soon as the Click event appears on the button, the code starts to execute. While other types of user interaction involve different method codes and a variety of event types, the basic process is interlinked.

2. Identifying UI Elements

The first step

To indicate which view the user interaction points to, we need to identify each interactive view in the application. In the example cited in the article, we will discuss only one view--but there are many different types of interactive view that you might use in future application development. In order for them to work methodically with each other, we need to set a unique id attribute for each view to identify and apply it to the entire application. First open our main layout file in Eclipse and switch to the XML edit tab. Next, we'll find the code we added for the button element, using the following syntax to assign it an ID:

    1. android:id= "@+id/mybutton"  

We need to assign an id attribute to each element used in the Android layout to help you identify each view element successfully. Note the "@+id" syntax in the code above. This prompts the Android tool to create a new ID in the project resource "R.java" file, and assigns it a unique text string within the application, known as "MyButton". In the rest of the XML layout code in your app, and even in other XML and Java files, we'll use this name to specify the button View. The current layout file is then saved.

Step Two

Open the main activity file in the application. We're going to add a little bit of Java code to it, but you don't have to worry about your own nasty Java level, just understand the approximate process that is relevant to dealing with user interaction. If your friends have never been in touch with Java before, please continue to follow our next tutorial, then look back to see what is now very simple. We want to create a variable in the activity class to reference the button View. After the start of the class declaration, after the starting content:

    1. Public class mainactivity extends Activity {

To add a variable declaration:

    1. Private Button Thebutton;

Our declaration contains visual attributes (next detail), variable types, and variable names. Eclipse may have an underscore in the button text section and prompt that the button cannot be resolved to a type. Since we are using the button type provided by the Android platform, it must be imported into the class file. Hover your mouse over the button text and eclipse will show us a list of recommendations. Select "Import" button (Android.widget). At the top of such a file, a list of import claims that can be freely expanded and collected is present.

Step Three

Now we can retrieve the reference to the button view in the layout and save the reference in the variable we created. In my activity OnCreate method, the following line of code is followed by the layout settings:

    1. Setcontentview (R.layout.activity_main);

Enter a new line of code to retrieve the button as follows:

    1. Thebutton = (Button) Findviewbyid ();

Enter another period "." --eclipse displays a list of existing ID values. Currently we only add an ID value, select the ID name we set for the button-that is, "MyButton".

You will use this method regularly to implement resource references in Java code. Now we should have the following line of code:

    1. Thebutton = (Button) Findviewbyid (R.id.mybutton);

This statement assigns the button view reference to the new variable we just created, which is designed to implement view recognition with its ID.

3. Monitoring Events

The first step

When requested, the Android system detects events only on the view. So we need to assign a listener to the view. There are several different ways to assign listeners, but let's start with the simplest: listening and responding with clicks from the activity class itself. The Declaration line is extended at the beginning of the class by the following:

    1. Public  class mainactivity extends Activity implements Onclicklistener {

As previously mentioned, Eclipse warns of the "Onclicklistener" type again. The old way, the mouse hover over the error content and import according to the requirements-select "Import ' Onclicklistener ' (Android.view. View) ". Here, you can see how eclipse helps us manage the components of the project. Now it also shows another error message, suggesting that we need to implement a method. Regardless of it, this problem is put to the back to solve.

The "Implements Onclicklistener" part of the code means that the activity class will take a specific set of interfaces. The next time we'll delve deeper into its specifics-it essentially means that the class will provide a special kind of functionality, which in our case allows you to handle the click action.

Step Two

Return to the activity OnCreate method. Add a new line of code below the line of code where we assign the button view reference to a variable by ID:

    1. Thebutton.setonclicklistener (this);

This line commands the application to listen for click Actions on the button. The "This" in parentheses specifies the object that handles the click operation. In the example in this article, the object refers to the activity class running the instance itself.

4. Responding to Events

The first step

Now we have been able to respond to button clicks. At the end of the class OnCreate method, add a closing parenthesis:

    1. Thebutton.setonclicklistener (this);

Add the following method summary:

    1. Public void OnClick (View v) {
    2. //respond to click  
    3. }

Go through the import process again, hover over "view" and select "Import" View (Android.view). Since we have ordered the click on the Class Monitor button, the method will start executing (its contents, or "Method ontology", will be placed between the two curly braces) when the click Operation occurs. The "View V" is a parameter to the method, which means that the method will be processed as a reference to the clicked View, so that we can identify it.

Step Two

In the OnClick method, we first need to check which view is clicked. We've only set a single click-through mechanism, but the application may need to handle multiple view clicks. In the method ontology, check that the view parameters that have been passed are the buttons we refer to in the variables:

    1. if(V.getid () ==thebutton.getid ()) {
    2. //the button was clicked  
    3. }

This is a conditional statement (then we'll discuss its structure in detail later) to check if the clicked view has the same ID as our variable. If this part of the content is executed, we can conclude that the button that is actually set is clicked. If the interaction element has only this one, then the testing process does not seem to be necessary, but you can imagine that when the clickable elements in the application are getting more and more, we must determine which of the triggers are triggered when the onclick executes.

Step Three

In the If condition section of the onclick, we can respond to the button click action. The response depends on the role of the button in the actual application, but in this case we're just trying to demonstrate the whole process. Add the following code:

    1. Thebutton.settext ("Ouch");

Here we simply change the text content displayed on the button after it is clicked. Now everyone's OnClick method should look like this:

    1. public void OnClick (View v) {
    2. //respond to click  
    3. if (V.getid () ==thebutton.getid ()) {
    4. //the button was clicked  
    5. Thebutton.settext ("Ouch");
    6. }
    7. }

For the effect of clicking on the button on the virtual device. We'll talk about how to get the application running on top of the physical and virtual devices, but now you just have to look at the response results.

5. Alternatives and options

The first step

We've shown a way to handle button clicks on Android, but this is not the only way. Another notable alternative is to add the following to a button in the XML layout:

    1. android:onclick= "ButtonClicked"  

The code above will specify the name of the method to be executed when the button is clicked. The corresponding method should be added to the activity class displayed in the layout. That way, we don't have to add a lot of code to the activity class, including creating a button variable, saving a view reference in it, enforcing onclicklistener, or setting a dedicated click Listener class for the button. In this example, we can instead add the OnClick method to the class by adding the following code, which uses the same code to achieve consistent operation effects:

    1. Public void buttonclicked (View v) {
    2. Button Thebutton = (button) v;
    3. Thebutton.settext ("Ouch");

Although this approach may seem simpler, the process of using Java to point a reference to a layout element deserves serious attention-and is often used in future application development processes. Also, if you have multiple clickable items in your layout, you might prefer to handle all the click events in the same way-in which case the scenario mentioned earlier in the article would be more desirable.

In addition to the two scenarios mentioned in the article, there are many other ways to achieve the click-Processing task on the view, but the others are more complicated and less suitable to use as a beginner.

Step Two

In this tutorial, we learned how to handle button click events in an Android system in the most basic way. The platform also provides the ability to handle a range of other user events for different view types, including long presses, keystrokes, touch, and more. Interested friends can refer to the Android Developer's Guide to learn about the various kinds of event processing tasks they may be exposed to in future project development work.

Summarize

In this section, we explored how to follow the basic process to implement the response of the user click button in the Android UI. Today's content is bucket compared to the full set of Android user interactions, but you should be able to understand the backbone from this generic approach and guide yourself to develop results that match user input habits in future projects. In the other tutorials in this series, we'll look at the most essential features of the Java language to achieve one brilliant victory in the learning of Android development.

Original link: http://mobile.tutsplus.com/tutorials/android/android-sdk-user-interaction/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.