游戏邦在:
杂志专栏:
gamerboom.com订阅到鲜果订阅到抓虾google reader订阅到有道订阅到QQ邮箱订阅到帮看

Android SDK游戏开发之用户交互设计

发布时间:2013-12-04 14:41:13 Tags:,,,,

作者:Sue Smith

简介

在本篇教程中,我们将检测并回应用户在之前添加的Button元素中的点击。这包含应用中主要Activity类的一些Java程序。如果你没用过Java也不用担心,只需遵循着如下步骤便可。我们将在下一部分进一步分析Java语法,以确保你清楚以前有关所需语言的内容,从而有效完成最初的Android开发任务。

你可以基于Android使用不同的方法去处理用户交互问题。我们将主要着眼于两大经典的方法去检测用户在按键上的点击,即包含添加一些较小的XML代码以及执行一些Java处理过程。在Android上存在各种不同的互动UI元素能够接收到各种类型的用户输入。你关于这种输入的处理必须适应考虑中的UI条款,不过全过程仍保持大致相同。我们将使用按键开始在Android上探索用户交互问题,因为这是在最简单也是最常使用的元素中。

1.用户交互基础

在我们讨论细节前,让我先为那些刚刚接触应用开发的人解释一些UI理念。为了创造应用互动,我们想要基于特殊的元素去检测用户交互。就像我们之前所看到的,在Android上这些是Views,而在这种情况下它们是Buttons。为了做到这点,我们需要伴随着View“听取”用户交互。尽管Android主要运行在触屏手机设备上,我们仍然能够使用那些针对于计算机互动而开发的语言。例如,你将看到“点击”这一词用于表示鼠标点击或指尖碰触/轻敲等动作。

用户能够基于各种方式与应用进行互动。他们可以轻敲,滑动,并“长时间按压”。当其中一种方式出现时,这便是所谓的“事件”。因此我们想要设置应用去听取特殊UI项目中出现的特殊事件。在这种情况下,我们将听取Button中的点击(或轻敲/碰触)。

我们想要回应并听取用户事件。为了做到这点我们将添加代码到Java Activity类中去听取并回应按键点击。这一代码会在点击出现在按键上时执行。相同的过程也用于处理带有任何View类型的用户交互,尽管方法代码在不同事件类型中发生着变化。

2.识别UI元素

步骤1

为了明确用户与哪个View进行互动,我们需要在应用中识别每个互动View。我们最初值拥有一个,但是你的未来应用可能会拥有各种类型的互动View。为了实现这种情况,我们提供了任何所需的View去识别一个能够用于应用中的特别ID属性。

在Eclipse中打开你的主要布局文件,并切换到XML编辑栏。定位在我们为Button元素所添加的代码。添加一个ID去使用如下语法:

android:id=”@+id/myButton”

你需要你在Android布局中使用的许多元素的ID属性,因为它们能够帮助你识别View。助于“@+id”语法。这提示了Android工具在项目资源“R.java”文件中去创造一个新的ID,并明确了一个文本字符串(在应用中也是独特的),也就是“myButton”。在XML布局代码的其它部分,以及在其它XML和Java文件中,我们将使用这一名称去识别Button View。保存你的布局文件。

步骤2

打开你的应用主要Activity文件。我们将添加一些Java代码,而如果你的Java还未准备好也不用担心,你只需要尝试着去理解用户交互处理中所包含的基本过程便可。如果你刚接触Java,当你完成下一篇教程时你便能够回顾本篇教程进行更深入的理解。我们将在类中创造一个变量去参考Button View。在类声明的最上方,在起始行之后添加如下:

public class MainActivity extends Activity {

添加变量声明:

private Button theButton;

我们明确了可见性,变量类型以及名称。Eclipse也许会用错误的信息“Button不能转变成类型”去强调“Button”文本。我们正在使用Android平台所提供的Button类型,所以我们必须将这一内容输入类文件中。让你的鼠标徘徊在“Button”文本上,Eclipse将用一列建议去提示你。选择“Import‘Button’(android.widget)”。这添加到了你能够在类文件最上方附近扩展并瓦解的输入声明列表中。

activity class(from tutsplus)

activity class(from tutsplus)

步骤3

现在我们可以在布局中检索参考到Button View中,在我们所创造的变量中储存这一参考。在你的Activity onCreate方法中,也就是在如下行后我们,设置了布局:

setContentView(R.layout.activity_main);

进入一个新行如下检索Button:

theButton = (Button)findViewById();

在“findViewById()”的括号中,Eclipse将使用一列资源类型给你提示。选择“id”。

resource type(from tutsplus)

resource type(from tutsplus)

输入另外一个句点“.”——Eclipse将呈现一列现有的ID值。到目前为止我们只添加了一个。从列表中选择我们为Button所设置的ID名称(“myButton”)。

ID values(from tutsplus)

ID values(from tutsplus)

当你需要在Java代码中参考资源时你将有规律地使用这一程序。现在你应该拥有如下内容:

theButton = (Button)findViewById(R.id.myButton);

这一声明将Button View参考分配到我们创造的新变量中,并使用其ID识别了View。

3.听取事件

步骤1

Android系统只会在我们命令时才在View上检测事件。因此我们需要分配一个监听器到View。我们可以基于许多不同的方式做到这点,但是让我们选择最简单的方法:让Activity类本身去听取并回应点击。在类最上方,如下扩展打开声明:

public class MainActivity extends Activity implements OnClickListener {

与之前一样Eclipse将告诫你警惕“OnClickListener”类型。徘徊在错误间,就像之前那样选择一个输入,选择“Import‘OnClickListener’(android.view.View)”。在此你可以看到在项目中Eclipse如何帮助你管理材料。它现在呈现的另一个错误信息告诉我们必须执行一个方法。我们将在之后解决这一错误。

这一“implements OnClickListener”代码表示Activity类将执行一个特殊的界面。我们将在之后更详细地着眼于这一实践—-它意味着类将提供特殊类型的函数,在这种情况下函数将允许我们处理点击。

步骤2

回到Activity onCreate方法。在你使用其ID分配Button View参考到变量中的那一行后面添加如下内容:

theButton.setOnClickListener(this);

这一行命令应用去听取按键中的点击。括号中的“this”制定了处理点击的对象。在这种情况下,这是Activity类本身的运行实例。

4.回应事件

步骤1

现在我们可以回应按键点击了。在类onCreate方法闭括号后:

theButton.setOnClickListener(this);
}

添加如下方法概述:

public void onClick(View v){
//respond to click }

再次执行输入过程,徘徊在“View”并选择“Import ‘View’(android.view)”。因为我们命令类去听取按键上的点击,所以当点击出现时,这一方法的内容将执行(内容,或“方法实体”将被放置在开括号和闭括号之间)。“View v”是方法的一个参数,这意味着方法收到一个参考到点击View中,所以我们可以识别到它。

步骤2

在onClick方法中,我们最先需要检查哪个View被点击。对于点击监听我们只有一个设置,但是应用在之后可能会处理多个View上的点击。在方法实体中,检查已经通过的View参数是否是我们在变量中拥有参考的按键:

if(v.getId()==theButton.getId()){
//the button was clicked }

这是一个条件声明,即根据我们所拥有的变量去检查点击View ID。如果这一组块的内容开始执行,我们便知道我们设置监听的按键被点击。当我们只拥有一个互动元素时,所有的这些测试可能看起来是不必要的,但是就像你所想象的那样,当你拥有一个以上的可点击元素,你便需要明确当onClick执行时哪个遭遇了点击。

步骤3

在onClick的if条件组块中,我们可以回应按键点击。回应取决于实际应用中的按键目的,但是在这种情况下我们正在呈现着过程。添加如下代码:

theButton.setText(“Ouch”);

当按键被点击时我们将改变呈现在按键上的文本。你的onClick方法应该如下出现:

public void onClick(View v){
//respond to click
if(v.getId()==theButton.getId()){
//the button was clicked
theButton.setText(“Ouch”);
}
}

以下是点击按键后虚拟设备上出现的结果。我们将在之后运行于真正和虚拟设备上,所以你将看到运作中的结果!

Ouch(from tutsplus)

Ouch(from tutsplus)

5.替代选择和选择

步骤1

我们演示了一种方法在Android上处理按键点击,但是还有其它方法。在XML布局中,一个替代选择值得注意的一点便是添加如下属性到你的按键上:

android:onClick=”buttonClicked”

当按键被点击时,这制定了执行的方法名称。这一方法应该被添加到Activity类中。这删除了对于你添加到Activity类中的所有代码的需求,包括创造Button变量,储存View参考到里面,执行OnClickListener,并为按键设置类作为点击监听器等。在这种情况下,比起添加onClick方法到累赘红,你可以添加如下代码:

public void buttonClicked(View v){
Button theButton = (Button)v;
theButton.setText(“Ouch”);
}

尽管这看起来可能很简单,但是在Java中检索参考到布局元素中的过程值得进一步去了解,就像你将会发现自己经常那么做。同样地如果你的布局带有多个可点击条款,你可能会更想要在一个方法中处理所有有点击事件,你可以使用上述所列出的第一个方法做到这点。

除了我们在此所探索的,还存在两种方法去处理View上的点击,但我们所列出的是最简单且最适合你的第一个项目的方法。

步骤2

在这一教程中我们完成了在Android上处理按键点击的基本过程。平台为不同View提供了一些其它的用户事件类型,包括长时间点击,按键按压和碰触事件。

总结

在这一部分中,我们探索了当你想要在Android UI上回应用户按键点击时需要遵循的基本过程。事实上除了我们所讨论到的,Android上还有其它更多用户交互方法,而现在你需要做的只是理解用户输入处理的基本方法,这将对你的最初项目带去很大的帮助。你可以将我们在本文中学到的内容作为创造自己Android UI技能的基础。而在下一部分教程中,我们将经历Java语言的最基本功能,为了更好地掌握Android开发,你需要真正去熟悉这些内容。

本文为游戏邦/gamerboom.com编译,拒绝任何不保留版权的转载,如需转载请联系:游戏邦

Android SDK: User Interaction

By Sue Smith

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:

android:id=”@+id/myButton”

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:

public class MainActivity extends Activity {

Add the variable declaration:

private Button theButton;

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.

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:

setContentView(R.layout.activity_main);

Enter a new line to retrieve the Button as follows:

theButton = (Button)findViewById();

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

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.

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

theButton = (Button)findViewById(R.id.myButton);

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.

public class MainActivity extends Activity implements OnClickListener {

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:

theButton.setOnClickListener(this);

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:

theButton.setOnClickListener(this);
}

Add the following method outline:

public void onClick(View v){
//respond to click }

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:

if(v.getId()==theButton.getId()){
//the button was clicked }

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:

theButton.setText(“Ouch”);

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

public void onClick(View v){
//respond to click
if(v.getId()==theButton.getId()){
//the button was clicked
theButton.setText(“Ouch”);
}
}

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!

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:

android:onClick=”buttonClicked”

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):

public void buttonClicked(View v){
Button theButton = (Button)v;
theButton.setText(“Ouch”);
}

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.(source:tutsplus)


上一篇:

下一篇: