第四課:創建基本用戶介面(一)創建按鈕事件

首先,如上幾課所教的,創建一個基本的Android Application Project。你會見到你的Project將如下:

PIC01_Project_Structure

在這裡要介紹幾個folder給大家,分別係src,res,gen folder:

src folder就是你的Java Code的地方,所有的Program Logic等等也是在這個folder裡面。

res folder是放著你的resource,包括icon,layout,value(string,color)等等也是這裡。

gen folder就是自動產生的Java檔案,理論上是不該改的,裡面有的主要是resource的id等。

另外AndroidManifest.xml是一個十分重要的file,整個App所需的permission,每一個Activity等也需要在那裡列出,當你需要創建一個新Activity或要用到手機的硬體等等,就可能要改動。

在接下來的幾課,小編將會教大家寫一個會以不同方法向用家打招呼的App,以認識Android的一些基本組件。

PIC02_Panel

開啟第一個Activity的layout file,你會見到左手邊會有著不同的組件,將來用到的話小編會解釋組件的用法。今次我們要用的是TextView,EditText,Button。TextView是用來顯示字串的,EditText是讓用家可以輸入字串,Button就是按鈕一個。你可以從左手邊拉出組件並修改組件特性,或是在改寫XML Code為如下:

[code language=”xml”]
<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="vertical" >

<TextView

android:id="@+id/textView_greeting"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello" />

<EditText

android:id="@+id/editText_name"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter your name here"

android:inputType="text" />

<Button

android:id="@+id/button_ok"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@android:string/ok" >

</Button>

</LinearLayout>

[/code]

android:id就是為這個組件的ID,之後在Java裡就是用這一個ID去找出個別組件,android:hint就是EditText的輸入提示,而這裡你可以見到使用了三種字串(”@string/hello”,”Enter your name here”,”@android:string/ok”)。

“@string/hello”是自行創建的字串,你需要在res->values->strings.xml加入這個字串。

“Enter your name here”是一個直接字串,用法上是可以的,但不建議這樣用,特別是如果是多地區多語言的更加不贊成。

“@android:string/ok”是直接使用Android系統的內建字串,如果有合用的直接使用即可。

完成後的layout應如下:

PIC03_Layout

然後修改MainActivity.java如下:

[code language=”java”]

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

private TextView tvGreeting;

private EditText etName;

private Button bnOk;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

tvGreeting = (TextView) findViewById(R.id.textView_greeting);

etName = (EditText) findViewById(R.id.editText_name);

bnOk = (Button) findViewById(R.id.button_ok);

bnOk.setOnClickListener(this);

}

@Override

public void onClick(View v) {

String name = etName.getText().toString();

tvGreeting.setText(R.string.hello);

tvGreeting.append(" " + name);

}

}

[/code]

在這裡要認識setContentView就是指定這個Activity要用哪個layout,而findViewById就是將這個layout裡的不同組件以ID作配對。要注意的是在要為Button設立事件監聽器(setOnClickListener),而監聽器以Interface的形式嵌入在MainActivity當中,所以Button的事件在onClick入面建立即可。

發表回覆