本範例基於早期 Android SDK 1.5 + Eclipse + ADT 環境,展示最基礎的 UI 佈局與事件處理。雖然工具鏈已更新(Android Studio + Gradle),但核心 API(LinearLayout、Button、EditText、AlertDialog)至今仍是入門必修。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/edtInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="EditText01" />
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show" />
<Button
android:id="@+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear" />
</LinearLayout>
</LinearLayout>
結構說明:外層垂直 LinearLayout 包含輸入框與內層水平按鈕容器;內層 gravity="center" 讓兩按鈕置中。
package com.studio.android;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class HelloAndroid extends Activity {
private Button btnShow, btnClear;
private EditText edtInput;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 1. 綁定 View
btnShow = findViewById(R.id.btnShow);
btnClear = findViewById(R.id.btnClear);
edtInput = findViewById(R.id.edtInput);
// 2. 共用點擊監聽器
OnClickListener listener = new ClickListener();
btnShow.setOnClickListener(listener);
btnClear.setOnClickListener(listener);
}
private class ClickListener implements OnClickListener {
@Override
public void onClick(View v) {
if (v == btnShow) {
new AlertDialog.Builder(HelloAndroid.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Information")
.setMessage(edtInput.getText())
.show();
} else if (v == btnClear) {
edtInput.setText("HelloAndroid");
}
}
}
}
| API | 用途 |
|---|---|
setContentView(R.layout.main) | 載入 XML 佈局並解析成 View 階層 |
findViewById() | 依 ID 取得 View 實例,需轉型 |
View.OnClickListener | 單點擊事件介面,單一方法 onClick(View) |
AlertDialog.Builder | 建構者模式快速建立對話框,支援鏈式調用 |
edtInput.getText() | 取得 Editable,自動轉 CharSequence 顯示 |
findViewById,編譯期型別安全。MaterialButton、TextInputEditText 提供更豐富樣式。此範例雖簡單,但涵蓋 Android 四大核心概念:佈局 XML、View 綁定、事件監聽、對話框互動。建議初學者手動輸入程式碼、觀察 Logcat、嘗試修改屬性值,建立肌肉記憶。