Xamarin.Android開發入門——Hello,Android快速上手

Hello, Android Quickstart

在指南的第一部分,我們創建一個打電話的應用,基礎功能為:將輸入含有字母和數字的電話號碼轉化為純數字號碼,然后撥打此號碼。最終界面如下:

下面開始練習。

系統及環境要求

Xamarin.Android需要以下任一環境

  • 系統:OS X Yosemite及以上;最新版Xamarin Studio

  • 系統:Windows 7及以上;最新版Xamarin Studio

  • 系統:Windows 7及以上;Visual Studio專業版或更高版本

本教程假定您已安裝最新版Xamarin.Android。

模擬器配置

如果你使用Google的Android SDK模擬器,建議配置硬件加速。

如果你使用Visual Studio的Android模擬器,則Hyper-V必須啟用。

操作演練

  1. 啟動Visual Studio

  1. 點擊開始界面里的 開始-新建項目 來創建項目

  1. 在 新建項目 對話框中,點擊 C#-Android ,然后選擇 Blank App(Android) 模板。將項目命名為 Phoneword 。點擊 確定 創建新項目

  1. 項目創建成功后,在解決方案管理器中展開 Resources 文件夾里的 layout 文件夾。雙擊 Main.axml 文件打開Android界面設計器,如下圖所示:

  1. 選中設計界面中的 Hello World,Click Me! 按鈕,并按 Delete 鍵刪除它。 在工具箱(左側區域)的搜索框中輸入 text ,然后拖動控件 Text(Large) 到設計界面(中間區域)中:

注:新版模板里已沒有按鈕,可略過刪除

  1. 選中 Text(Large) 控件,然后在屬性面板中修改 text 屬性值為 Enter a Phoneword ,如圖所示:

  1. 下一步,在工具箱中拖動一個 Plain Text 控件到設計界面中,將它放置在 Text(Large) 控件下面。

注:可以通過搜索框幫助我們快速定位到具體的控件。

  1. 選中 Plain Text 控件,在屬性面板中修改 id 屬性值為 @+id/PhoneNumberText ,同時修改 text 屬性值為 1-855-XAMARIN :

  1. 在工具箱中拖動一個 Button 到設計界面,并將其放置在 Plain Text 控件下面:

  1. 選中 Button ,在屬性面板中修改 id 屬性值為 @+id/TranslateButton ,同時修改 text 屬性值為 Translate:

  1. 下一步,再從工具箱中拖動第二個 Button 到設計界面,并將其放置于 Translate 按鈕下面:

  1. 選中新添加的 Button 控件,在屬性面板中修改 id 屬性值為 @+id/CallButton ,并將 text 屬性值改為 Call :

按下 CTRL+S 鍵保存上述操作。

  1. 現在,我們添加轉換電話號碼的代碼(從數字字母組合的號碼到純數字號碼)。首先,我們添加一個新的文件:在解決方案管理器中,右擊 Phoneword 項目,然后選擇 添加—新建項...

  1. 在 添加新項 對話框中,選擇 Visual C# > Code 中的 Code File ,并將其命名為 PhoneTranslator.cs

注:最新中文版開發環境中, 添加新項 下結構中,可以選擇 Visual C#-代碼 里的 代碼文件 ,也可以選擇 Visual C#-Android 里的 Class 。—— 都是建立.cs文件

  1. 移除掉模板代碼,并用以下代碼替換:

新版模板文件本身就是個空文件

using System.Text;
    using System;

namespace Core
{
    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);
                }
                // otherwise we've skipped a non-numeric char
            }
            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;
        }
    }
}</code></pre> 

然后點擊 文件-保存 (或按 CTRL+S 鍵)來保存 PhoneTranslator.cs 文件。 重新生成解決方案,以保證沒有編譯錯誤。

  1. 接下來,我們添加代碼與UI界面連接起來。 雙擊解決方案管理器中的 MainActivity.cs 文件,打開后在 MainActivity 類中添加后臺代碼:

  1. 首先配置 Translate 按鈕。在 MainActivity 類中找到 OnCreate 方法。我們將會在 OnCreate 方法中的 base.OnCreate(bundle) 和 SetContentView(Resource.Layout.Main) 之后添加代碼。移除模板按鈕處理代碼( 沒有就不用管 ),最后代碼類似于下面示例:

    using System;
    using Android.App;
    using Android.Content;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;
    
    namespace Phoneword
    {
        [Activity (Label = "Phoneword", MainLauncher = true)]
        public class MainActivity : Activity
        {
            protected override void OnCreate (Bundle bundle)
            {
                base.OnCreate (bundle);
    
                // Set our view from the "main" layout resource
                SetContentView (Resource.Layout.Main);
    
                // Our code will go here
            }
        }
    }
  2. 下一步,我們需要為 layout 文件中的控件(之前界面設計器中拖的控件)添加對應的引用。在 OnCreate 方法中添加如下代碼:(添加在 SetContentView 之后)

    // Get our UI controls from the loaded layout:
    EditText phoneNumberText = FindViewById<EditText>(Resource.Id.PhoneNumberText);
    Button translateButton = FindViewById<Button>(Resource.Id.TranslateButton);
    Button callButton = FindViewById<Button>(Resource.Id.CallButton);
  3. 首先,為 Translate 按鈕添加點擊事件處理。將如下代碼添加至 OnCreate 方法中(在上一步的代碼之后):

    // Disable the "Call" button
    callButton.Enabled = false;
    
    // Add code to translate number
    string translatedNumber = string.Empty;
    
    translateButton.Click += (object sender, EventArgs e) =>
    {
        // Translate user's alphanumeric phone number to numeric
        translatedNumber = Core.PhonewordTranslator.ToNumber(phoneNumberText.Text);
        if (String.IsNullOrWhiteSpace(translatedNumber))
        {
            callButton.Text = "Call";
            callButton.Enabled = false;
        }
        else
        {
            callButton.Text = "Call " + translatedNumber;
            callButton.Enabled = true;
        }
    };
  4. 其次,為 Call 按鈕添加點擊事件處理。在之前的 Translate 按鈕事件代碼之后添加如下代碼:

    callButton.Click += (object sender, EventArgs e) =>
    {
        // On "Call" button click, try to dial phone number.
        var callDialog = new AlertDialog.Builder(this);
        callDialog.SetMessage("Call " + translatedNumber + "?");
        callDialog.SetNeutralButton("Call", delegate {
            // Create intent to dial phone
            var callIntent = new Intent(Intent.ActionCall);
            callIntent.SetData(Android.Net.Uri.Parse("tel:" + translatedNumber));
            StartActivity(callIntent);
        });
        callDialog.SetNegativeButton("Cancel", delegate { });
    
        // Show the alert dialog to the user and wait for response.
        callDialog.Show();
    };
  5. 最后,我們需要給應用分配撥打電話的權限。我們可以通過Android Manifest來編輯應用的權限。雙擊解決方案管理器中 Phoneword 項目下的 Properties 項,然后選擇 Android Manifest 打開界面:

在 Required Permissions 中,勾選 CALL_PHONE 權限

  1. 點擊 文件-全部保存 (或者按 CTRL+SHIFT+S 鍵)來保存所有操作,然后點擊 生成-重新生成解決方案 (或者按 CTRL+SHIFT+B 鍵)來編譯應用程序。當程序編譯完成后,Visual Studio會在其左下角顯示編譯成功的消息:

如果有錯誤,請檢查是否按照以上步驟操作,修正至可以生成成功。如果遇到生成錯誤,例如: Resource does not exist in the current context ,請校驗 MainActivity.cs 中的命名空間與項目名稱( Phoneword )是否一致,然后重新生成解決方案。如果仍然有生成錯誤,請確認你已安裝的最新版的Xamarin.Android的更新。

  1. 現在我們已經建立的可用的應用程序,接下來我們完善應用程序的內容。首先,編輯 MainActivity 的 Label 值。此 Label 值顯示在Android系統的頁面頂部,表示用戶正在使用哪個應用程序。在 MainActivity 類的頂部,將 Label 值修改為 Phone Word ,如下所示:

    namespace Phoneword
    {
        [Activity (Label = "Phone Word", MainLauncher = true)]
        public class MainActivity : Activity
        {
            ...
        }
    }
  2. 然后,設置應用的圖標。首先從 Xamarin App Icons set 下載并解壓,展開 Resources 下的 drawable 文件夾,并將現有的 Icon.png 刪除(右鍵-刪除):

在以下彈出確認框中點擊 OK :

  1. 然后,右擊 drawable 文件夾,選擇 添加-現有項... :

  1. 在文件選擇對話框中,瀏覽解壓后的Xamarin App Icons目錄,打開 drawable 文件夾,選擇 Icon.png 并點擊 添加 :

  1. 下一步,添加Xamarin App Icons中剩余的 drawable-* 的文件夾到項目中。那些文件夾為不同設備,不同分辨率提供不同的圖標以便更好的顯示。打開文件瀏覽窗口,定位到Xamarin App Icons的解壓目錄,然后選中 drawable-* 目錄。

拖動這些文件夾至Visual Studio的 解決方案管理器 面板中的 Resources 文件夾上。至此,可以在右側 解決方案管理器 中可以看到項目已經包含那些文件夾:

  1. 接下來,在Android Manifest界面中的 Application Icon 下拉框中選擇 @drawable/Icon 作為應用的圖標:

  1. 最后,我們可以通過將應用部署到模擬器上進行測試。在本文中,我們使用Android AVD Manager配置的虛擬設備(名稱為 Nexus 5(KitKat) )——關于如何配置見:同樣,你也可以使用預置配置下拉框中的任意一個。

在將應用部署到模擬器之前,我們先配置下應用所支持的最低Android版本,以此保證可以在我們選擇的虛擬設備上運行。在Visual Studio中,雙擊 Properties 打開 Application 頁面。在 Minimun Android to target 配置中,選擇匹配你虛擬設備的API Level。在本文示例中,我們選擇API Level 19,所以應用將運行在 Nexus 5(KitKat) 虛擬設備上。

  1. 下一步,點擊工具欄中下拉菜單將應用部署到 Nexus 5(KitKat) ,如下圖所示:

Visual Studio會在安裝和啟動應用之前將文檔拷貝到模擬器。

  1. 下圖展示了 Phoneword 應用在Android SDK模擬器上的運行效果。點擊 Translate 按鈕會更新 Call 按鈕的text值,然后點擊 Call 按鈕會調用一個撥打電話確認框,如下面右圖所示:

至此,第一個Xamarin.Android應用程序創建完成。

 

來自:http://www.shisujie.com/blog/Hello-Android-Quickstart

 

 本文由用戶 ylxbsoftware 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!