(一)Building Your First App建立你的第一个应用

来源:互联网 发布:php 打印数组 编辑:程序博客网 时间:2024/04/29 10:40

首发自依鹏CSDN博客,转载注明出处:http://blog.csdn.net/m0_37240709/article/details/77017812

Building Your First App建立你的第一个应用

Welcome to Android application development!
欢迎来到Android应用程序开发。
This class teaches you how to build your first Android app. You’ll learn how to create an Android project with Android Studio and run a debuggable version of the app. You'll also learn some fundamentals of Android app design, including how to build a simple user interface and handle user input.
这个课程教你如何构建你的第一个Android应用程序。你将学习如何使用Android Studio创建一个Android项目,并运行该应用程序的调试版本。你还将了解Android应用程序设计的一些基本原理,包括如何构建一个简单的用户界面和处理用户输入。
Before you start this class, download and install Android Studio.

在开始这门课程之前,要先下载并安装Android Studio。

1、Creating an Android Project创建一个安卓项目

This lesson shows you how to create a new Android project with Android Studio and describes some of the files in the project.
本课程将向您展示如何使用Android Studio创建一个新的Android项目,并描述项目中的一些文件。
1.In Android Studio, create a new project:
  • If you don't have a project opened, in the Welcome screen, click New Project.
  • If you have a project opened, from the File menu, select New Project. The Create New Project screen appears.
1.在Android Studio中,创建一个新项目:
  • 如果您没有一个打开的项目,在“Welcome”界面中,单击“New project”创建新的项目。
  • 如果您已经打开了一个项目,从“File”菜单中选择“New Project”。创建新项目的“Create New Project”窗口就会出现了。

2.Fill out the fields on the screen. For Application Name use "My First App". For Company Domain, use "example.com". For the other fields, use the default values and click Next
Here's a brief explanation of each field:
  • Application Name is the app name that appears to users.
  • Company domain provides a qualifier that will be appended to the package name; Android Studio will remember this qualifier for each new project you create.
  • Package name is the fully qualified name for the project (following the same rules as those for naming packages in the Java programming language). Your package name must be unique across all packages installed on the Android system. You can Edit this value independently from the application name or the company domain.
  • Project location is the directory on your system that holds the project files.
2.把屏幕上的字段填满。应用程序名称“Application Name”使用“My First App”。对于公司域名“Company Domain”,使用“example.com”。对于其他字段,使用默认值并单击Next。
以下是对每个字段的简要说明:
  • Application Name 是呈现给用户的应用名称。
  • Company domain 是公司的域名,提供了一个附加在包名上的限定词。Android Studio会为你创建的每个新项目记住这个限定符。
  • Package name 包名,项目的完全限定名(遵循Java编程语言中对包命名的规则)。你的包名必须与安装在安卓系统上的所有的包名不同。你可以单独修改包名,与应用程序名或公司域名是不相干的。
  • Project location是您的系统中保存项目文件的目录。

3.Under Target Android Devices, accept the default values and click Next.
The Minimum Required SDK is the earliest version of Android that your app supports, indicated using the API level. To support as many devices as possible, you should set this to the lowest version available that allows your app to provide its core feature set. If any feature of your app is possible only on newer versions of Android and it's not critical to the app's core feature set, you can enable the feature only when running on the versions that support it (as discussed in Supporting Different Platform Versions).
3.在目标安卓设备“Target Android Devices”下面,选择默认值,点击Next。
最低要求的SDK是你的应用支持的最早的Android版本,使用API级别表示。为了支持尽可能多的设备,您应该将其设置为可用的最低版本,这个版本要允许您的应用程序提供其核心功能集。如果你的应用程序的任何功能只在最新版本的安卓系统上运行,而且它对应用的核心功能集不重要,那么你只能在支持它的版本上运行该功能(在“Supporting Different Platform Versions”中讨论)。

4.Under Add an Activity to Mobile, select Empty Activity and click Next.
4.在“Add an Activity to Mobile”下面,选择“Empty Activity”,点击Next。

5.Under Customize the Activity, accept the default values and click Finish.
5.在“Customize the Activity”下面,选择默认值,点击Finish完成。

Your Android project is now a basic "Hello World" app that contains some default files. Take a moment to review the most important of these:
你的Android项目现在是一个基本的“Hello World”应用程序,它包含一些默认文件。花点时间回顾一下其中最重要的部分:

app/src/main/java/com.example.myfirstapp/MainActivity.java
This file appears in Android Studio after the New Project wizard finishes. It contains the class definition for the activity you created earlier. When you build and run the app, the Activity starts and loads the layout file that says "Hello World!"
这个文件在新项目向导完成后出现在Android Studio中。它包含您之前创建的activity的类定义。当您构建并运行该应用程序时,该activity启动并加载布局显示着“Hello World!”文件。

app/src/main/res/layout/activity_main.xml
This XML file defines the layout of the activity. It contains a TextView element with the text "Hello world!".
这个XML文件定义了activity的布局。它包含了text值是“Hello world!”的TextView元素。

app/src/main/AndroidManifest.xml
The manifest file describes the fundamental characteristics of the app and defines each of its components. You'll revisit this file as you follow these lessons and add more components to your app.
清单文件描述了应用程序的基本特征,并定义了它的每个组件。当你随着课程学习向你的应用中添加组件时,你会再次访问这个文件。

app/build.gradle
Android Studio uses Gradle to compile and build your app. There is a build.gradle file for each module of your project, as well as a build.gradle file for the entire project. Usually, you're only interested in the build.gradle file for the module, in this case the app or application module. This is where your app's build dependencies are set, including the defaultConfig settings:
Android Studio使用Gradle来编译和构建你的应用程序。它既属于你项目的每一个模块,也属于你整个项目。通常,你可能对当前应用或应用模块中的build.gradle文件更感兴趣。这是你的应用建立构建依赖关系的地方,包括defaultConfig 的设置:

  • compiledSdkVersion is the platform version against which you will compile your app. By default, this is set to the latest version of Android available in your SDK. By default, this is set to the latest version of Android SDK installed on your development machine. You can still build your app to support older versions, but setting this to the latest version allows you to enable new features and optimize your app for a great user experience on the latest devices.
  • compiledSdkVersion是对你将要编译的应用程序的平台版本。默认情况下,这将被设置为你的SDK中最新的Android版本。默认情况下,这将设置为安装在您开发设备上的最新版本的Android SDK。你仍然可以构建你的应用来支持旧版本,但将其设置为最新版本允许你使用新功能,并优化你的应用以获得最新设备上的更好的用户体验。


  • applicationId is the fully qualified package name for your application that you specified in the New Project wizard.
  • applicationId是您在新项目向导中指定的应用程序的完全限定包名。


  • minSdkVersion is the Minimum SDK version you specified during the New Project wizard. This is the earliest version of the Android SDK that your app supports.
  • minSdkVersion是您在新项目向导中指定的最低SDK版本。这是你的应用支持的Android SDK的最早版本。


  • targetSdkVersion indicates the highest version of Android with which you have tested your application. As new versions of Android become available, you should test your app on the new version and update this value to match the latest API level and thereby take advantage of new platform features. For more information, read Supporting Different Platform Versions.
  • targetSdkVersion表示您对应用程序进行测试的Android最高版本。随着新版本的Android版本的出现,你应该在新版本上测试你的应用,并更新这个值以匹配最新的API级别,从而利用新的平台特性。要了解更多信息,请阅读“支持不同的平台版本”。

See Building Your Project with Gradle for more information about Gradle.
要了解更多Gradle信息,参阅“通过Gradle构建你的项目”。

Note also the /res subdirectories that contain the resources for your application:
还要注意包含应用程序资源的/res子目录:

drawable-<density>/

Directories for drawable resources, other than launcher icons, designed for various densities.
这是一个图片资源目录,除了启动图标,也用来设计不同分辨率的图片。

layout/
Directory for files that define your app's user interface like activity_main.xml, discussed above, which describes a basic layout for the MainActivity class.
用于定义应用程序用户界面的文件目录,比如活动activity_main.xml,上面讨论了,它描述了MainActivity类的基本布局。

menu/

Directory for files that define your app's menu items.为定义应用程序菜单项的文件目录。
mipmap/
Launcher icons reside in the mipmap/ folder rather than the drawable/ folders. This folder contains the ic_launcher.png image that appears when you run the default app.
启动器图标位于mipmap/文件夹中,而不是drawable/文件夹。这个文件夹包含的 ic_launcher.png,是运行默认应用程序时出现的图像。

values/
Directory for other XML files that contain a collection of resources, such as string and color definitions.

用于包含资源集合的其他XML文件的目录,例如字符串和颜色定义。


To run the app, continue to the next lesson.

要运行这款应用,请继续下一节课。


2、Running Your App 运行你的应用

In the previous lesson, you created an Android project. The project contains a default app that displays "Hello World". In this lesson, you will run the app on a device or emulator.
在上一节课中,您创建了一个Android项目。该项目包含一个显示“Hello World”的默认应用程序。在本课程中,您将在设备或模拟器上运行该应用程序。

2.1、Run on a Real Device运行在真机上

Set up your device as follows:
按照下面的方法设置你的设备:

1.Connect your device to your development machine with a USB cable. If you're developing on Windows, you might need to install the appropriate USB driver for your device. For help installing drivers, see the OEM USB Drivers document.
用USB连接线将你的设备连接到你的开发机器上。如果你在Windows上开发,你可能需要为你的设备安装合适的USB驱动程序。要帮助安装驱动程序,请参阅OEM USB驱动程序文档。

2.Enable USB debugging on your device by going to Settings > Developer options.
在你的设备上启用USB调试,通过Settings > Developer options。
Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options.
注意:在Android 4.2和更新版本中,开发者选项默认是隐藏的。要想让它可用,你可以去Settings > About phone中点击Build number7次。返回到前面的屏幕以找到开发者选项。

Run the app from Android Studio as follows:
按如下方式运行Android Studio的应用程序:
1.In Android Studio, select your project and click Run from the toolbar.在Android Studio中,选择您的项目并单击工具栏上的Run。
2.In the Select Deployment Target window, select your device, and click OK.
在Select Deployment Target窗口中,选择你的设备,点击OK。

Android Studio installs the app on your connected device and starts it.
Android Studio会在你的连接设备上安装这个应用然后启动它。

2.2、Run on the Emulator运行在模拟器上

Before you run your app on an emulator, you need to create an Android Virtual Device (AVD) definition. An AVD definition defines the characteristics of an Android phone, tablet, Android Wear, or Android TV device that you want to simulate in the Android Emulator.
在模拟器上运行您的应用程序之前,您需要创建一个Android虚拟设备(AVD)描述。AVD描述定义了Android手机、平板电脑、Android Wear或Android TV设备的特性,你想在Android模拟器中模拟的特性。

Create an AVD Definition as follows:
按照如下方式创建一个AVD描述:
1.Launch the Android Virtual Device Manager by selecting Tools > Android > AVD Manager, or by clicking the AVD Manager icon in the toolbar.
启动Android虚拟设备管理器,选择工具是Tools > Android > AVD Manager,或者是点击工具栏上的AVD管理器图标。
2.On the AVD Manager main screen, click Create Virtual Device.
在AVD管理器主屏幕上,单击Create虚拟设备。
3.In the Select Hardware page, select a phone device, such as Nexus 6, then click Next.
在选择硬件的页面中,选择一个手机设备,如Nexus 6,然后点击Next。
4.In the Select Image page, choose the desired system image for the AVD and click Next.
在选择图像页面中,为AVD选择所需的系统映像并单击Next
5.Verify the configuration settings (for your first AVD, leave all the settings as they are), and then click Finish.
验证配置设置(对于您的第一个AVD,保留所有设置),然后单击Finish。
For more information about using AVDs, see Create and Manage Virtual Devices.
有关使用AVDs的更多信息,请参见创建和管理虚拟设备。

Run the app from Android Studio as follows:
按如下运行Android Studio的应用程序:

In Android Studio, select your project and click Run from the toolbar.
在Android Studio中,选择您的项目并单击工具栏中的Run。
In the Select Deployment Target window, select your emulator and click OK.
在Select Deployment Target窗口,选择你的模拟器并单击OK。
It can take a few minutes for the emulator to start. You may have to unlock the screen. When you do, My First App appears on the emulator screen.
模拟器可以花几分钟的时间来启动。你可能需要解锁屏幕。当你这么做的时候,My First App应用程序出现在模拟器屏幕上。
That's how you build and run your Android app on the emulator! To start developing, continue to the next lesson.

这就是你在模拟器上构建和运行你的Android应用程序的方式!要开始开发应用程序,请继续下一节课。


3、Building a Simple User Interface构建一个简单的用户界面

In this lesson, you create a layout in XML that includes a text field and a button. In the next lesson, your app responds when the button is pressed by sending the content of the text field to another activity.
在本节课程中,你将在XML文件中创建一个布局,其中包括一个文本框和一个按钮。在下一节课中,当按钮按下按钮时,你的应用会做出响应,将文本框的内容发送到另一个Activity。

The graphical user interface for an Android app is built using a hierarchy of View and ViewGroup objects. View objects are usually UI widgets such as buttons or text fields. ViewGroup objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.
Android应用程序的图形用户界面是使用有层次结构的View和ViewGroup对象来构建的。View对象通常是UI小部件,例如按钮或文本框。ViewGroup对象是不可见的视图容器,它们定义了子视图的布局方式,比如网格布局或垂直列表布局。

Android provides an XML vocabulary that corresponds to the subclasses of View and ViewGroup so you can define your UI in XML using a hierarchy of UI elements.
Android提供了一个XML词汇表,它对应于View和ViewGroup的子类,因此您可以使用UI元素的层次结构来定义您的UI。

Layouts are subclasses of the ViewGroup. In this exercise, you'll work with a LinearLayout.
布局是ViewGroup的子类。在这个练习中,您将使用一个线性布局。


图1所示。视图组对象如何在布局中形成分支并包含其他视图对象

3.1、Create a Linear Layout构建线性布局

1.From the res/layout/ directory, open the activity_main.xml file.
在res/layout/目录中,打开activity_main.xml文件。
This XML file defines the layout of your activity. It contains the default "Hello World" text view.
XML文件定义了activity的布局。它包含显示着“Hello World”的默认文本视图。

2.When you open a layout file, you’re first shown the design editor in the Layout Editor. For this lesson, you work directly with the XML, so click the Text tab to switch to the text editor.
打开布局文件时,首先在布局编辑器中显示设计编辑器。对于这个课程,您可以直接使用XML,因此单击Text选项卡切换到文本编辑器。

3.Replace the contents of the file with the following XML:
使用下面的XML替换文件中的内容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">
</LinearLayout>


LinearLayout is a view group (a subclass of ViewGroup) that lays out child views in either a vertical or horizontal orientation, as specified by the android:orientation attribute. Each child of a LinearLayout appears on the screen in the order in which it appears in the XML.
线性布局是一个视图组(ViewGroup的一个子类),它可以在垂直或水平方向上排列子视图,这是由android:orientation属性指定的。每个线性布局中的视图出现在屏幕上的顺序便是它排列XML文件中的顺序。

Two other attributes, android:layout_width and android:layout_height, are required for all views in order to specify their size.
另外两个属性,android:layoutwidth和android:layoutheight,用来限定视图的大小,对所有视图都是需要的。

Because the LinearLayout is the root view in the layout, it should fill the entire screen area that's available to the app by setting the width and height to "match_parent". This value declares that the view should expand its width or height to match the width or height of the parent view.
因为线性布局是布局中的根视图,它应该可以将宽度和高度设置为“匹配父元素”来填充应用程序中可用的整个屏幕区域。该值声明视图应该扩展其宽度或高度以匹配父视图的宽度或高度。

For more information about layout properties, see the Layout guide.
有关布局属性的更多信息,请参见布局指南。

3.2、Add a Text Field添加一个文本域

In the activity_main.xml file, within the <LinearLayout> element, add the following <EditText> element:
在activity_main.xml文件的<LinearLayout>元素之内,添加一个<EditText>元素,如下所示:
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">
   <EditText android:id="@+id/edit_message"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:hint="@string/edit_message" />

</LinearLayout>


Here is a description of the attributes in the <EditText> you added:
下面是对您在<EditText> 中添加的属性的描述:

android:id
This provides a unique identifier for the view, which you can use to reference the object from your app code, such as to read and manipulate the object (you'll see this in the next lesson).
这为视图提供了一个惟一的标识符,您可以通过它在应用程序代码中来引用视图对象,诸如读取和操作该视图对象(在下一节中您将看到这个)。
The at sign (@) is required when you're referring to any resource object from XML. It is followed by the resource type (id in this case), a slash, then the resource name (edit_message).
当您引用XML中的任何资源对象时,需要使用@符号,接下来是资源类型(本例中为id)、一个斜杠、然后是资源名(edit_message)。
The plus sign (+) before the resource type is needed only when you're defining a resource ID for the first time. When you compile the app, the SDK tools use the ID name to create a new resource ID in your project's gen/R.java file that refers to the EditText element. With the resource ID declared once this way, other references to the ID do not need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not needed for concrete resources such as strings or layouts. See the sidebox for more information about resource objects.
只有当你第一次定义资源ID时,才需要在资源类型前加上加号(+)。在编译该应用程序时,SDK工具使用ID名在你项目的gen/R.java文件中创建一个新的资源ID,这个资源ID关联着你的EditText元素。资源ID声明一次之后,其他对ID的引用不需要加号。仅在指定新资源ID时需要使用加号,而对诸如字符串或布局这样的具体资源是不需要的。有关资源对象的更多信息,请参阅侧栏。

android:layout_width and android:layout_height
Instead of using specific sizes for the width and height, the "wrap_content" value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use "match_parent", then the EditText element would fill the screen, because it would match the size of the parent LinearLayout. For more information, see the Layouts guide.
“wrap_content”属性值并没有使宽度和高度使用特定的大小,而是指定视图的大小应该与视图内容的大小一样大,它是包裹内容的。如果您使用的是“match_parent”,那么EditText元素将填充屏幕,因为它将匹配其父元素LinearLayout的大小。要了解更多信息,请参阅布局指南。

android:hint
This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the "@string/edit_message" value refers to a string resource defined in a separate file. Because this refers to a concrete resource (not just an identifier), it does not need the plus sign. However, because you haven't defined the string resource yet, you’ll see a compiler error at first. You'll fix this in the next section by defining the string.
这是在文本框为空时显示的默认字符串。“@string/editmessage”属性值不使用硬编码的字符串作为值,而是引用在一个单独文件中定义的字符串资源。因为这指的是一个具体的资源(不仅仅是一个标识符),它不需要加号。然而,因为您还没有定义字符串资源,最初会看到一个编译错误。在下一节中,将通过定义字符串来解决这个问题。
Note: This string resource has the same name as the element ID: edit_message. However, references to resources are always scoped by the resource type (such as id or string), so using the same name does not cause collisions.
注意:这个字符串资源与元素属性ID的名称相同:edit_message。但是,对资源的引用总是由资源类型(例如id或字符串)确定的,所以使用相同的名称不会导致冲突。

3.3、Add String Resources添加字符串资源

By default, your Android project includes a string resource file at res/values/strings.xml. Here, you'll add two new strings.
默认情况下,您的Android项目包括一个字符串资源文件,它是/valu/strings.xml。你将向文件中添加两个新的字符串。
1.From the res/values/ directory, open strings.xml.
在res/values/目录下,打开strings.xml文件。
2.Add two strings so that your file looks like this:
添加两个字符串,你的文件将会是如下样子:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">My First App</string>
   <string name="edit_message">Enter a message</string>
   <string name="button_send">Send</string>

</resources>


For text in the user interface, always specify each string as a resource. String resources allow you to manage all UI text in a single location, which makes the text easier to find and update. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string resource.
对于用户界面中的文本,始终将每个字符串指定为一个资源。字符串资源允许您在一个位置管理所有的UI文本,这使得文本更容易查找和更新。外部化管理字符串还允许您通过为每个字符串资源提供不同的语言版本定义,来将应用程序本地化为不同的语言版本。
For more information about using string resources to localize your app for other languages, see the Supporting Different Devices class.
有关使用字符串资源将应用程序本地化为其他语言的更多信息,请参见支持不同的设备类。

3.4、Add a Button添加一个按钮

Go back to the activity_main.xml file and add a button after the <EditText>. Your file should look like this:
回到activity_main.xml文件,在<EditText>后面添加一个按钮。像下面这样:

<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <EditText android:id="@+id/edit_message"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:hint="@string/edit_message" />
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/button_send" />

</LinearLayout>


Note: This button doesn't need the android:id attribute, because it won't be referenced from the activity code.
注意:这个按钮不需要android:id属性,因为它不会从activity 代码中引用。

The layout is currently designed so that both the EditText and Button widgets are only as big as necessary to fit their content, as figure 2 shows.
目前设计的布局是为了让EditText和Button小部件尽可能的大,以适应它们的内容,如图2所示。

Figure 2. The EditText and Button widgets have their widths set to "wrap_content".
图2. EditText和Button 小部件的宽度设置为“包裹内容”。

This works fine for the button, but not as well for the text field, because the user might type something longer. It would be nice to fill the unused screen width with the text field. You can do this inside a LinearLayout with the weight property, which you can specify using the android:layout_weight attribute.
这个属性值对于按钮来说是很好的,但会与文本框来说不是那么好,因为文本框可能会输入更多的东西。使用文本域填充未使用的屏幕宽度是很不错的。您可以在一个带有权重属性的线性布局中完成这个操作,您可以使用android:layout权重属性指定。

The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. This works kind of like the amount of ingredients in a drink recipe: "2 parts soda, 1 part syrup" means two-thirds of the drink is soda. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.
权重值是一个数字,它指定每个视图相对于同级视图应该消耗的剩余空间的量。这就像饮料配方里的成分一样:“2份苏打水,1份糖浆”意味着三分之二的饮料是苏打水。例如,如果你给一个视图一个权重为2另一个权重为1,总和是3,所以第一个视图填满了剩余空间的2/3,第二个视图填充其余部分。如果你添加第三个视图,并让它的权重为1,那么第一个视图(权重为2)现在得到了剩余空间的1/2,而剩下的两个则得到1/4。

The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require.
所有视图默认权重值都是0,所以如果你将一个视图的权重值设置为大于0的数字,那么在其他视图被分配必须的空间后剩余的所有空间都将分配给这个视图。

3.5、Make the Input Box Fill in the Screen Width让输入框填满屏幕宽度

In activity_main.xml, modify the <EditText> so that the attributes look like this:
在activity_main.xml文件中,修改<EditText>的属性,像下面的样子:

<EditText android:id="@+id/edit_message"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:hint="@string/edit_message" />


Setting the width to zero (0dp) improves layout performance because using "wrap_content" as the width requires the system to calculate a width that is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space.
将宽度设置为0(0dp)可以提高布局性能,因为使用“包裹内容”作为宽度属性值要求系统计算宽度,而这一宽度最终是不相关的,因为权重值需要另一个宽度计算来填充剩余空间。

Figure 3. The EditText widget is given all the layout weight, so it fills the remaining space in the LinearLayout.
图3. EditText小部件被赋予了所有布局权重,因此它填充了线性布局中的剩余空间。

Here’s how your complete activity_main.xml layout file should now look:
这就是你完成的activity_main.xml布局文件,如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <EditText android:id="@+id/edit_message"
      android:layout_weight="1"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:hint="@string/edit_message" />
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/button_send" />
</LinearLayout>

3.6、Run Your App运行你的应用程序

This layout is applied by the default Activity class that the SDK tools generated when you created the project.
这个布局文件适用于你创建项目时SDK工具生成的默认Activity类。
To run the app and see the results, click Run 'app' in the toolbar.
在工具栏中点击“Run”运行你的应用程序,查看结果。
Continue to the next lesson to learn how to respond to button presses, read content from the text field, start another activity, and more.

在下面的课程中,我们将继续学习怎样响应按钮的点击,怎样从文本域中读取内容,怎样开启另一个activity,还有更多的知识。


4、Starting Another Activity 启动另一个Activity

After completing the previous lesson, you have an app that shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some code to MainActivity that starts a new activity when the user clicks the Send button.
在完成上一节课之后,你会有一个应用程序,它显示一个activity (一个屏幕),带有一个文本框和一个按钮。在本课程中,您将向MainActivity添加一些代码,当用户单击Send按钮时,将启动一个新activity。

4.1、Respond to the Send Button响应Send按钮

1.In the file res/layout/activity_main.xml, add the android:onClick attribute to the <Button> element as shown below:
在res/layout/activity_main.xml中,给<Button>元素添加一个属性android:onClick,如下:
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />


This attribute tells the system to call the sendMessage() method in your activity whenever a user clicks on the button.
当用户点击按钮是,这个属性告诉系统去掉用activity中的sendMessage()方法。

2.In the file java/com.example.myfirstapp/MainActivity.java, add the sendMessage() method stub as shown below:
在java/com.example.myfirstapp/MainActivity.java文件中添加sendMessage()方法,代码如下:
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
     
   /** Called when the user clicks the Send button */
   public void sendMessage(View view) {
      // Do something in response to button
   }
}


In order for the system to match this method to the method name given to android:onClick, the signature must be exactly as shown. Specifically, the method must:
为了让系统将这个方法与android:onClick属性给出的的方法名相匹配,签名必须准确地显示出来。具体来说,方法必须:
  • Be public方法共有
  • Have a void return value无返回值
  • Have a View as the only parameter (this will be the View that was clicked)只有View一个参数(这个View就是被点击的视图)


Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity.

接下来,您将填充这个方法来读取文本字段的内容,并将该文本传递给另一个activity。

4.2、Build an Intent创建一个Intent对象

An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but in this lesson, your intent starts another activity.
Intent是在不同的组件之间提供运行时绑定的对象(例如两个activitie)。Intent标志着一个应用“想要做点事情”。您可以使用Intent来进行各种各样的任务,但是在本课程中,您的意图将启动另一个activity。

In MainActivity.java, add the code shown below to sendMessage():
在MainActivity.java文件的sendMessage()方法中添加如下代码:

public class MainActivity extends AppCompatActivity {
   public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
     
   /** Called when the user clicks the Send button */
   public void sendMessage(View view) {
      Intent intent = new Intent(this, DisplayMessageActivity.class);
      EditText editText = (EditText) findViewById(R.id.edit_message);
      String message = editText.getText().toString();
      intent.putExtra(EXTRA_MESSAGE, message);
      startActivity(intent);
   }
}


Note: Android Studio will display Cannot resolve symbol errors because the code references classes like Intent and EditText that have not been imported. To import these classes, you can either 1) use Android Studio's "import class" functionality by pressing Alt + Enter (Option + Return on Mac) or 2) manually add import statements at the top of the file.
注意:Android Studio将显示“Cannot resolve symbol”错误,因为代码引用的类如Intent和EditText没有导入。要导入这些类,您可以选择1)使用Android Studio的“导入类”功能,通过按下Alt+Enter(Mac上的Option + Return)或2)手工添加导入语句到文件的顶部。

There’s a lot going on in sendMessage(), so let’s explain what's going on.
sendMessage()方法有很多事情要做,让我们来解释一下发生了什么。

The Intent constructor takes two parameters:
Intent的构造方法接收两个参数:
  • A Context as its first parameter (this is used because the Activity class is a subclass of Context). 上下文对象是第一个参数(之所以被使用是因为Activity类是上下文的子类)。
  • The Class of the app component to which the system should deliver the Intent (in this case, the activity that should be started).系统交付给Intent的应用组件的类(也就是要被启动的Activity)。

Note: The reference to DisplayMessageActivity will raise an error in Android Studio because the class doesn’t exist yet. Ignore the error for now; you’ll create the class soon.
注意:对于DisplayMessageActivity的引用将会在Android Studio中引起一个错误,因为这个类还不存在。现在就忽略这个错误;你很快就会创建这个类。

The putExtra() method adds the EditText's value to the intent. An Intent can carry data types as key-value pairs called extras. Your key is a public constant EXTRA_MESSAGE because the next activity uses the key to retrive the text value. It's a good practice to define keys for intent extras using your app's package name as a prefix. This ensures the keys are unique, in case your app interacts with other apps.
putExtra()方法将EditText的值添加到intent对象中。Intent对象可以携带键值对类型的数据,被称为extras。这个key是一个公有的常量EXTRA_MESSAGE,因为下一个activity还要使用它来取出这个文本值。使用报名前缀来定义intent extras的键是一个非常好的做法。这种做法确保这个键是唯一的,以防你的应用于其他应用进行交互。
The startActivity() method starts an instance of the DisplayMessageActivity specified by the Intent. Now you need to create the class.
startActivity()方法启动由intent指定的DisplayMessageActivity的一个实例。现在你需要来创建这个类。

4.3、Create the Second Activity创建第二个Activity

1.In the Project window, right-click the app folder and select New > Activity > Empty Activity.
在Project窗口,右击app文件夹,选择New > Activity > Empty Activity。

2.In the Configure Activity window, enter "DisplayMessageActivity" for Activity Name and click Finish
在Configure Activity窗口中,Activity Name项输入DisplayMessageActivity,单击Finish按钮。

Android Studio automatically does three things:
Android Studio默默的做了三件事:
  • Creates the class DisplayMessageActivity.java with an implementation of the required onCreate() method.创建一个DisplayMessageActivity.java文件,并实现了onCreate()方法。
  • Creates the corresponding layout file activity_display_message.xml.生成了相应的布局文件activity_display_message.xml。
  • Adds the required <activity> element in AndroidManifest.xml. 在清单文件中添加了Activity的声明。

If you run the app and click the Send button on the first activity, the second activity starts but is empty. This is because the second activity uses the default empty layout provided by the template.
如果您运行该应用程序并在第一个activity中单击Send按钮,那么第二个activity将启动,但它是空的。这是因为第二个activity使用模板提供的默认的空布局。

4.4、Display the Message显示消息

Now you will modify the second activity to display the message that was passed by the first activity.现在你将修改第二个Activity,来显示第一个Activity传递过来的数据。

1.In DisplayMessageActivity.java, add the following code to the onCreate() method:
在DisplayMessageActivity.java文件的onCreate()方法中添加如下代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_display_message);
    
   Intent intent = getIntent();
   String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
   TextView textView = new TextView(this);
   textView.setTextSize(40);
   textView.setText(message);
    
   ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
   layout.addView(textView);
}


2.Press Alt + Enter (option + return on Mac) to import missing classes.
按Alt+Enter(Mac通过option+return)导入确实的类。

There’s a lot going on here, so let’s explain:
这里有很多东西,我们来解释一下:

  • The call getIntent() grabs the intent that started the activity. Every Activity is invoked by an Intent, regardless of how the user navigated there. The call getStringExtra() retrieves the data from the first activity.
  • 通过调用getIntent()方法来获取启动这个Activity的intent对象。不论用户如何操作,每一个Activity都是被一个intent唤起的。调用getStringExtra()从第一个Activity中取回数据。


  • You programmatically create a TextView and set its size and message.
  • 以编程方式创建一个TextView,给它设置大小和信息。


  • You add the TextView to the layout identified by R.id.activity_display_message. You cast the layout to ViewGroup because it is the superclass of all layouts and contains the addView() method.
  • 将TextView添加到由R.id.activity displaymessage所标识的布局中。将布局转换为ViewGroup,因为它是所有布局的超类,并包含addView()方法。

Note: The XML layout generated by previous versions of Android Studio might not include the android:id attribute. The call findViewById() will fail if the layout does not have the android:id attribute. If this is the case, open activity_display_message.xml and add the attribute android:id="@+id/activity_display_message" to the layout element.
注意:以前版本的Android Studio生成的XML布局可能不包括Android:id属性。如果布局没有android:id属性,那么调用findViewById()将失败。如果是这种情况,则打开activity_display_message.xml并向布局元素添加属性android:id=”@+id/activity_display_message”。

You can now run the app. When it opens, type a message in the text field, and click Send. The second activity replaces the first one on the screen, showing the message you entered in the first activity.
你现在可以运行这个应用程序。当它打开时,在文本框中输入一个消息,然后点击Send。第二个activity将替换屏幕上的第一个activity,显示您在第一个activity中输入的消息。

That's it, you've built your first Android app!
就是这样,你已经建立了你的第一个Android应用程序!
To learn more, follow the link below to the next class.
要学习更多,请遵循下面的链接到



阅读全文
1 0
原创粉丝点击