1. 程式人生 > >[Andriod官方訓練教程]建立你的第一個App之建立一個簡單的使用者介面

[Andriod官方訓練教程]建立你的第一個App之建立一個簡單的使用者介面

---------------------------------------------------------------------------------

The graphical user interface for an Android app is built using a hierarchy of View and  objects. View objects are usually UI widgets such as buttons or text fields and  objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.

一個Android app的圖形使用者介面是使用View 和 物件的層次結構來建立的。 View 物件通常是一些UI部件,例如buttons 或 text fields ,而  物件是一些不可見的容器,它們定義了子介面是如何排布的,例如在一個網格或一個垂直列表裡。

Android provides an XML vocabulary that corresponds to the subclasses of View and  so you can define your UI in XML using a hierarchy of UI elements.

Android提供了一個XML詞彙表,它對應了

View 和  的子類,因此你可以在XML中使用UI元素的層次結構來定義你自己的UI。

Alternative Layouts

Declaring your UI layout in XML rather than runtime code is useful for several reasons, but it's especially important so you can create different layouts for different screen sizes. For example, you can create two versions of a layout and tell the system to use one on "small" screens and the other on "large" screens. For more information, see the class about 

Supporting Different Devices.

可供選擇的佈局

在XML中宣告你的UI佈局,而非執行時刻的程式碼中,在一些時候是有用的,尤其是你可以為不同的螢幕大小建立不同的佈局。例如,你可以建立兩個版本的同一佈局,然後告訴系統,在“小”螢幕上使用其中一個,而在“大”螢幕上使用另一個。更多的資訊,請見Supporting Different Devices一課。

Figure 1. Illustration of how  objects form branches in the layout and contain other View objects.

圖1. 示例 物件如何構成佈局分支幷包含其他View 物件。

In this lesson, you'll create a layout in XML that includes a text field and a button. In the following lesson, you'll respond when the button is pressed by sending the content of the text field to another activity.

在這節課中,你將在XML中建立一個佈局,它包含了一個文字區域和一個按鍵。在下面的課程中,在按鍵被按下時,你將會通過向另一個activity傳送文字編輯域中的內容來做出響應。

Create a Linear Layout —— 建立一個線性佈局

Open the activity_main.xml file from the res/layout/ directory.

開啟res/layout/ 目錄下的activity_main.xml檔案。

Note: In Eclipse, when you open a layout file, you’re first shown the Graphical Layout editor. This is an editor that helps you build layouts using WYSIWYG tools. For this lesson, you’re going to work directly with the XML, so click the activity_main.xml tab at the bottom of the screen to open the XML editor.

注意:在Eclipse裡,當你開啟一個佈局檔案時,你最先看到的是佈局編輯器的圖形介面。這個編輯器幫助你使用WYSIWYG來建立佈局。在本節課,你將直接用XML工作,因此點選螢幕底部的activity_main.xml 標籤來開啟XML編輯器。

The BlankActivity template you chose when you created this project includes the activity_main.xml file with a  root view and a  child view.

在你建立這個專案時選擇的 BlankActivity 模板包含了activity_main.xml

First, delete the  element and change the  element to . Then add the android:orientation attribute and set it to "horizontal". The result looks like this:

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns: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>

 is a view group (a subclass of ) that lays out child views in either a vertical or horizontal orientation, as specified by the android:orientation attribute. Each child of a appears on the screen in the order in which it appears in the XML.

The other two attributes, android:layout_width and android:layout_height, are required for all views in order to specify their size.

Because the  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.

因為LinearLayout是這個佈局的子檢視,它應該填充整個可用的螢幕區域,這通過設定長寬值為"match_parent"來實現。這個值表明該檢視應該擴充套件它的長或寬來匹配父檢視的長或寬。

For more information about layout properties, see the Layout guide.

更多有關佈局性質的資訊請見佈局指南。

Add a Text Field —— 新增一個文字框

To create a user-editable text field, add an  element inside the .

Like every View object, you must define certain XML attributes to specify the  object's properties. Here’s how you should declare it inside the  element:

和每個View物件相同,你必須定義確定的XML屬性來指定 物件的性質。下面展示了你應該如何在

<EditTextandroid:id="@+id/edit_message"android:layout_width="wrap_content"android:layout_height="wrap_content"android:hint="@string/edit_message"/>

About resource objects

A resource object is simply a unique integer name that's associated with an app resource, such as a bitmap, layout file, or string.

Every resource has a corresponding resource object defined in your project's gen/R.java file. You can use the object names in the R class to refer to your resources, such as when you need to specify a string value for the android:hint attribute. You can also create arbitrary resource IDs that you associate with a view using the android:id attribute, which allows you to reference that view from other code.

The SDK tools generate the R.java each time you compile your app. You should never modify this file by hand.

For more information, read the guide to Providing Resources.

關於資源物件

一個資源物件只是一個唯一的整型名字,並與一個app資源相關聯,例如一個位圖,佈局檔案,或字串。

每個資源都有一個對應的資源物件在你專案的gen/R.java 檔案中。你可以使用 R 類來引用你的資源,例如當你需要為android:hint 屬性指定一個字串值。你也可以使用android:id 屬性建立任意的資源IDs並與一個檢視相關聯,這允許你在其他程式碼中引用這個檢視。

每當你編譯你的app時,SDK工具就會生成R.java。你不應該手動修改該檔案。

About these attributes:

關於這些性質:

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

這個為該檢視提供了一個唯一的識別符號,你可以在你的app程式碼中使用它來引用這個物件,例如用於讀取並操作該物件(在下一節課中你將會看到)。

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檔案中引用任意資源時,你需要at符號(@)。緊跟著的是該資源型別(本例中是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  element. Once the resource ID is 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時才需要。當你編譯這個app時,SDK工具使用這個ID名字在你的專案的gen/R.java 檔案裡,來建立一個新的資源ID並指向 元素。一旦這個資源ID通過這種方式被宣告,其他對這個ID的引用就不再需要加號。當且僅當定義一個新的資源ID時使用加號,對於具體的資源,例如字串或佈局則是不需要的。關於資源物件的更多資訊,請見旁邊的方框。

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  element would fill the screen, because it would match the size of the parent . For more information, see the Layouts guide. 不是使用特定的長寬大小,"wrap_content"值指定了檢視大小應該恰好適應檢視內容。如果你使用"match_parent",那麼 將會填充螢幕,因為它要匹配父檢視LinearLayout的大小。更多資訊請見佈局指南。
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/edit_message"引用了一個單獨的檔案中定義的一個字串。因為這個引用了一個具體的資源(而不僅僅是一個識別符號),它不需要加號。但是,因為你還沒有定義這個字串,你一開始將會看到一個編譯錯誤。在下一章節中通過定義這個字串,你將會糾正這個錯誤。

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 或 string),因此使用同一個名字不會引起衝突。

Add String Resources —— 新增字串資源

When you need to add text in the user interface, you should always specify each string as a resource. String resources allow you to manage all UI text in a single location, which makes it easier to find and update text. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string resource.

當你需要在使用者介面中新增文字時,你應該總是將每個字串指定為一個資源。字串資源允許你在一個單獨的位置管理所有的UI文字,這使得查詢和更新文字變得更加容易。外化字串也允許你通過提供可供選擇的字串資源,來支援不同的語言。

By default, your Android project includes a string resource file at res/values/strings.xml. Add a new string named "edit_message" and set the value to "Enter a message." (You can delete the "hello_world" string.)

預設下,你的Android專案res/values/strings.xml下包含了一個字串資原始檔。新增一個名為"edit_message"的新的字串,並將值設為"Enter a message"。(你可以刪除"hello_world"字串了。

While you’re in this file, also add a "Send" string for the button you’ll soon add, called "button_send".

當你編輯該檔案時,同時為你將要新增的按鍵新增一個"Send"字串,叫做"button_send"

The result for strings.xml looks like this:

strings.xml 的結果如下:

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

For more information about using string resources to localize your app for other languages, see the Supporting Different Devices class.

Add a Button —— 新增一個按鍵

Now add a  to the layout, immediately following the  element:

<Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/button_send"/>

The height and width are set to "wrap_content" so the button is only as big as necessary to fit the button's text. This button doesn't need the android:id attribute, because it won't be referenced from the activity code.

Make the Input Box Fill in the Screen Width

The layout is currently designed so that both the  and  widgets are only as big as necessary to fit their content, as shown in figure 2.

當前設計的佈局中, 和  部件的大小剛好適應它們的內容,正如圖2中顯示的一樣。

Figure 2. The  and  widgets have their widths set to "wrap_content".

圖2.  和  部件的寬度值設定為"wrap_content"

This works fine for the button, but not as well for the text field, because the user might type something longer. So, it would be nice to fill the unused screen width with the text field. You can do this inside a with the weight property, which you can specify using the android:layout_weight attribute.

這對於按鍵很適用,但卻不適合文字框,因為使用者可能鍵入更長的內容。因此,應該使用文字框來填充剩餘的未被適用的螢幕寬度。你可以在LinearLayout

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 vodka, 1 part coffee liqueur" means two-thirds of the drink is vodka. 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.

weight值指定了每個檢視佔據的剩餘空間的數量,相對於兄弟檢視的佔據量。這和一杯飲料食譜中的原料分量相似:“2分伏特加,一份咖啡甜酒”意味著三分之二的飲料是伏特加。例如,如果你給一個檢視的分量為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. So, to fill the remaining space in your layout with the  element, give it a weight of 1 and leave the button with no weight.

預設的所有檢視的分量為0,因此如果你只為一個檢視指定任何大於0的分量值,那麼在所有檢視被寄予需要的空間後,該檢視將會佔據剩餘所有空間。因此,在你的佈局中為了讓EditText元素佔據剩餘空間,賦予它分量值為1,並保留按鍵無分量值。

<EditTextandroid:layout_weight="1"
        ... />

In order to improve the layout efficiency when you specify the weight, you should change the width of the  to be zero (0dp). Setting the width to zero 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.

當你指定分量值時為了提高佈局的效率,你應該改變EditText的寬度值為0(0dp)。將寬度設定為0將會提高佈局的效能,因為使用g"wrap_content" 作為寬度將會要求系統最終計算一個無關的寬度因為分量值要求另一個寬度計算來填充剩餘空間。

<EditTextandroid:layout_weight="1"android:layout_width="0dp"
        ... />

Figure 3 shows the result when you assign all weight to the  element.

圖3展示了當你為 元素設定所有分量值後的結果。

Figure 3. The  widget is given all the layout weight, so fills the remaining space in the .

圖3.  部件被寄予所有的佈局分量,因此它填充

Here’s how your complete layout file should now look:

下面是完整佈局檔案:

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns: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"><EditTextandroid:id="@+id/edit_message"android:layout_weight="1"android:layout_width="0dp"android:layout_height="wrap_content"android:hint="@string/edit_message"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/button_send"/></LinearLayout>

This layout is applied by the default  class that the SDK tools generated when you created the project, so you can now run the app to see the results:

該佈局應用於預設的 類,它是在你建立專案時由SDK工具生成的,因此你現在可以執行app來看到結果了:

  • In Eclipse, click Run  from the toolbar. 在Eclipse裡,點選工具欄中的Run 
  • Or from a command line, change directories to the root of your Android project and execute: 或者在命令列中,改變目錄到你的Android專案的根目錄,並執行:
    ant debug
    adb install bin/MyFirstApp-debug.apk

Continue to the next lesson to learn how you can respond to button presses, read content from the text field, start another activity, and more.

下一節課你會學習如何響應按鍵的點選事件,從文字框中讀取內容,開始另一個activity,以及更多的內容。