編輯:關於 Android 程式設計
還記得第一次寫程式跑出成果時的悸動嗎?本文帶你用 C# 完成人生第一個 Android 應用——一個能把英文電話號碼轉成數字、撥號,並記錄所有撥打紀錄的小 App。透過它,你會對 Android 的基本架構與多螢幕導航有個全面的直觀認識。
別急著糾結程式碼裡的每個細節,那些概念後面都會逐一細說。現在,先享受把東西做出來的樂趣吧。


點「將文本轉換為數字」看結果;按下【轉換】鈕,若轉換成功,【撥號】鈕才會啟用;再按【撥號】鈕,就會跳出確認對話框,確認後即可撥號。
選擇範本 Blank App (Android),專案名 PhonewordApp。建立完成後,記得刪除 GettingStarted.Xamarin 這個廣告檔。

雙擊打開 Main.axml,先看看【Design】與【Source】兩個檢視,再刪掉預設的「Hello World, Click Me」按鈕。接著從工具箱依序拖入:
• Text (Large):id 設為 @+id/PhoneText,文字「電話」。
• Plain Text:id 設為 @+id/PhoneNumberText,文字「138 4912 2599」。
• Button:id 設為 @+id/buttonTranslate,文字「轉換」。
• Button:id 設為 @+id/buttonCall,文字「撥號」。

存檔後點【重新整理】,目的是讓系統產生資源的 ID,這樣後面寫 C# 時才有智慧提示可用。
先新增一個 PhoneTranslator.cs,負責把英文字母依手機九宮格鍵盤對應成數字:
using System.Text; namespace PhonewordApp { public static class PhonewordTranslator { public static string ToNumber(string raw) { if (string.IsNullOrWhiteSpace(raw)) { return ""; } else { raw = raw.ToUpperInvariant(); } var newNumber = new StringBuilder(); foreach (var c in raw) { if ("- 0123456789".Contains(c)) newNumber.Append(c); else { var result = TranslateToNumber(c); if (result != null) newNumber.Append(result); } } return newNumber.ToString(); } static bool Contains(this string keyString, char c) { return keyString.IndexOf(c) >= 0; } static int? TranslateToNumber(char c) { if ("ABC".Contains(c)) return 2; else if ("DEF".Contains(c)) return 3; else if ("GHI".Contains(c)) return 4; else if ("JKL".Contains(c)) return 5; else if ("MNO".Contains(c)) return 6; else if ("PQRS".Contains(c)) return 7; else if ("TUV".Contains(c)) return 8; else if ("WXYZ".Contains(c)) return 9; return null; } } }
接著改写 MainActivity.cs,把轉換、撥號與歷史紀錄的邏輯串起來:
using System; using Android.App; using Android.Content; using Android.Widget; using Android.OS; using System.Collections.Generic; namespace PhonewordApp { [Activity(Label = "PhonewordApp", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { static readonly List<string> phoneNumbers = new List<string>(); protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); var phoneNumberText = FindViewById<EditText>(Resource.Id.PhoneNumberText); var buttonTranslate = FindViewById<Button>(Resource.Id.buttonTranslate); var buttonCall = FindViewById<Button>(Resource.Id.buttonCall); buttonCall.Enabled = false; string translatedNumber = string.Empty; buttonTranslate.Click += (s, e) => { translatedNumber = PhonewordTranslator.ToNumber(phoneNumberText.Text); if (string.IsNullOrWhiteSpace(translatedNumber)) { buttonCall.Text = "撥號"; buttonCall.Enabled = false; } else { buttonCall.Text = "播出號碼:" + translatedNumber + ",單擊確認!"; buttonCall.Enabled = true; } }; var buttonCallHistory = FindViewById<Button>(Resource.Id.buttonCallHistory); buttonCallHistory.Click += (sender, e) => { var intent = new Intent(this, typeof(CallHistoryActivity)); intent.PutStringArrayListExtra("phone_numbers", phoneNumbers); StartActivity(intent); }; buttonCall.Click += (s, e) => { phoneNumbers.Add(translatedNumber); buttonCallHistory.Enabled = true; var callDialog = new AlertDialog.Builder(this); callDialog.SetMessage("電話:" + translatedNumber + ",撥號嗎?"); callDialog.SetNeutralButton("撥號", delegate { var callIntent = new Intent(Intent.ActionCall); callIntent.SetData(Android.Net.Uri.Parse("tel:" + translatedNumber)); StartActivity(callIntent); }); callDialog.SetNegativeButton("取消", delegate { }); callDialog.Show(); }; } } }
重新建置確保無誤後,別忘了到專案屬性中勾選【CALL PHONE】權限——少了它,App 就沒有撥號權限,功能會失敗。

撥號的核心其實就是三行:建立一個 Intent.ActionCall 意圖、設定 tel: 的 URI,再 StartActivity 啟動它。
先在 Strings.xml 補上字串資源:
<resources> …… <string name="CallHistory">撥號記錄</string> </resources>
存檔後重新整理或重新建置,讓 C# 能辨識它。接著在 Main.axml 拖入一個 Button,id 設為 @+id/buttonCallHistory、文字用 @string/CallHistory、enabled 設為 false。這裡用 @string 引用資源,比直接寫死文字更推薦,能有效提升效能。
再新增一個 CallHistoryActivity.cs,用 ListActivity 把傳入的號碼清單顯示出來:
namespace PhonewordApp { [Activity(Label = "CallHistoryActivity")] public class CallHistoryActivity : ListActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); var phoneNumbers = Intent.Extras.GetStringArrayList("phone_numbers") ?? new string[0]; this.ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, phoneNumbers); } } }
其中 c = a ?? b 的意思等同於:若 a 不為 null 則取 a,否則取 b。最後在 MainActivity 中透過 Intent 把號碼清單傳給第二個畫面即可。

到這裡,你已經完成了人生第一個用 C# 寫的 Android 應用——恭喜!
Git 分支管理入門:從快照、HEAD 到合併
分支的核心概念 使用分支的好處,是可以從主線開發中分離出來,在不影響主分支的情況下進行新功能、實驗或緊急修復。完成後再合併回主線,讓開發流程更有彈性。 Git 的分支之所
Android WebView 使用大全:loadUrl、loadData 與 JavaScript 雙向通信
WebView 是 Android 提供的網頁瀏覽元件,能載入遠端網頁,也能渲染本地 HTML。它本質上是一個完整的瀏覽器引擎,理解這一點,很多進階玩法就顺理成章了。以下
Activity 生命週期(四):暫停與恢復的時機和注意事項
在多數正常的應用場景中,前台 Activity 偶爾會被其他可視元件遮擋而進入暫停狀態。最典型的例子是彈出一個半透明的 Activity(例如對話框樣式的頁面):此時原
Android 登錄介面實戰:自定義輸入框與驗證碼
登錄介面的常見需求一個完整的登錄介面,通常不只是兩個輸入框。它還需要帳號密碼清空、空值提示、驗證碼校驗,以及清楚的錯誤回饋。自定義 DeletableEditText為了