編輯:關於 Android 程式設計
不論是為了日後的工作需求,還是眼下的專案,掌握行動開發都是一項值得投資的技能。而學習任何新技術,總得從最經典的 Hello World 開始,Android 自然也不例外。
初次打開 Android 開發工具 ADT,目錄結構難免讓人有點眼花撩亂。不過對照網路上各種結構說明後,慢慢就能理出頭緒。實作這個範例時,特別需要留意兩個地方:一個是放置後端程式碼的 src 目錄,另一個則是存放 XML 前台配置檔的 res/layout 目錄。
既然目標是「點擊按鈕後在 EditText 中顯示 Hello World!」,我們先打開 layout 檔,拖入一個 Button 和一個 EditText,最後的 XML 結構如下:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:clickable="true" android:text="Button" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button1" android:layout_alignBottom="@+id/button1" android:layout_toRightOf="@+id/button1" android:text="EditText" /> </RelativeLayout>
接著在後端程式碼中引入兩個必要的命名空間:
import android.widget.Button; import android.widget.EditText;
完整程式碼如下:
package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private Button myButton; private EditText myText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myButton = (Button)findViewById(R.id.button1); myText = (EditText)findViewById(R.id.editText1); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub myText.setText("Hello World!"); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
點擊執行按鈕,在模擬器中按下按鈕,就能看到如下圖所示的結果:

這一節就先到這裡,後續我們會繼續探索更多有趣的 Android 主題。
有興趣深入學習的讀者,可延伸閱讀本站專題:《Android 調試技巧與常見問題解決方法匯總》、《Android 開發入門與進階教程》、《Android 多媒體操作技巧匯總(音頻、視頻、錄音等)》、《Android 基本組件用法總結》、《Android 視圖 View 技巧總結》、《Android 布局 layout 技巧總結》與《Android 控件用法總結》。
希望本文能為你的 Android 程式設計之路開個好頭。
Android TimePicker 用法詳解:讓使用者挑選時分的完整範例
本文以一個可直接運行的範例,說明 TimePicker 與 TimePickerDialog 在 Android 中的用法,包含版面配置、Dialog 建立、結果回呼與時
Android NDK 實作你的第一個 HelloWorld(Eclipse + ADT 篇)
上一篇我們把 NDK 的開發環境搭好了。身為開發者,接下來當然要用一個 HelloWorld 來確認一切正常。 步驟一:建立 Android 專案 在 ADT 中新增一個
徹底搞懂 Android Intent Filter 的匹配機制
Intent 是什麼 在 Android 的世界裡,Intent 扮演著應用彼此溝通、協作的核心角色。你可以把它理解成一張「任務派工單」:它描述了這次操作要做什麼(動作)
Android 開發環境建置總整理(Eclipse 篇)
開始學 Android 開發,第一道關卡就是環境建置。這類文章網路上很多,本文想補充的是兩個常被忽略的環節:ADT 的下載技巧,以及 Eclipse 的配色調整。 一、