Xamarin 快速指南



Xamarin - 安裝

Xamarin 基於 .NET Framework 構建。它允許建立可在多個平臺上輕鬆執行的應用程式。在本教程中,我們將解釋如何使用 Xamarin 提供原生 iOS、Android 和 Windows 應用程式。

讓我們從討論如何在 Windows 和 Mac 系統上安裝 Xamarin 開始本教程。

系統要求

Windows

  • 至少具有 2GB RAM 並執行 Windows 7 或更高版本的計算機 (強烈推薦 Windows 8-10)

  • Visual Studio 2012 專業版或更高版本

  • 適用於 Visual Studio 的 Xamarin

Mac

  • 執行 OS X Yosemite (10.10) 或更高版本的 Mac 計算機
  • Xamarin iOS SDK
  • Apple 的 Xcode (7+) IDE 和 iOS SDK
  • Xamarin Studio

在 Windows 上安裝

https://www.xamarin.com/download 下載 Xamarin 安裝程式。在執行 Xamarin 安裝程式之前,請確保已在您的計算機上安裝 Android SDK 和 Java SDK。

執行下載的安裝程式以開始安裝過程:

  • 將出現 Xamarin 許可協議螢幕。單擊下一步按鈕以接受協議。

  • 安裝程式將搜尋任何缺失的元件,並提示您下載並安裝它們。

  • Xamarin 安裝完成後,單擊關閉按鈕退出,然後準備開始使用 Xamarin。

在 Mac 上安裝

  • 在您的 Mac 系統上下載 Xamarin Studio 安裝程式。

  • 執行您下載的 Xamarin 安裝程式,並按照安裝嚮導中的步驟操作。

  • 安裝完成後,您就可以開始在您的系統上使用 Xamarin 了。

Xamarin - 第一個應用程式

在本章中,我們將學習如何使用 Xamarin 建立一個小型 Android 應用程式。

Hello Xamarin!應用程式

首先,啟動 Visual Studio 的新例項,然後轉到檔案→新建→專案

Project

在出現的選單對話方塊上,轉到模板→Visual C#→Android→空白應用程式 (Android)

Blank App

為您的應用程式指定一個合適的名稱。在本例中,我們將其命名為“helloWorld”並將其儲存在提供的預設位置。接下來,單擊確定按鈕以載入新的“helloXamarin”專案。

解決方案中,開啟資源→佈局→Main.axml檔案。從設計檢視切換到檔案,並鍵入以下幾行程式碼來構建您的應用程式。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:background = "#d3d3d3" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
   <TextView 
      android:text = "@string/HelloXamarin" 
      android:textAppearance = "?android:attr/textAppearanceLarge" 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/textView2" 
      android:textColor = "@android:color/black" /> 
</LinearLayout>

在上面的程式碼中,我們建立了一個新的 Android textview。接下來,開啟 values 資料夾並雙擊Strings.xml以開啟它。在這裡,我們將儲存關於上面建立的按鈕的資訊和值。

<?xml version = "1.0" encoding = "utf-8"?> 
<resources> 
   <string name = "HelloXamarin">Hello World, I am Xamarin!</string> 
   <string name = "ApplicationName">helloWorld</string> 
</resources> 

開啟MainActivity.cs檔案,並將現有程式碼替換為以下幾行程式碼。

using System; 
using Android.App; 
using Android.Content; 
using Android.Runtime; 
using Android.Views; 
using Android.Widget; 
using Android.OS; 
 
namespace HelloXamarin { 
   public class MainActivity : Activity { 
      protected override void OnCreate(Bundle bundle) { 
         base.OnCreate(bundle); 
         SetContentView(Resource.Layout.Main); 
      } 
   } 
}

儲存應用程式。構建並執行它以在 Android 模擬器中顯示建立的應用程式。

Android Emulator

如果您沒有 Android 模擬器,請按照下一節中的步驟建立一個。

設定 Android 模擬器

在您的 Visual Studio 選單上,轉到工具→Android→Android 模擬器管理器。在出現的彈出視窗中,單擊建立按鈕。它將顯示以下螢幕。

Create new andriod virtual device

在上面的螢幕上,提供您想要的AVD 名稱。選擇適合您顯示器的裝置,例如 Nexus 4” 顯示器。選擇您的目標平臺。始終建議在最低目標平臺(例如 API 10 Android 2.3(薑餅))上進行測試,以確保您的應用程式可在所有 Android 平臺上執行。

填寫其餘欄位並單擊確定按鈕。您的模擬器現在已準備就緒。您可以從現有 Android 虛擬裝置列表中選擇它,然後單擊啟動以啟動它。

Emulator

修改 HelloXamarin 應用程式

在本節中,我們將修改我們的專案並建立一個按鈕,單擊該按鈕將顯示文字。開啟main.axml並切換到源檢視。在我們建立的textview之後,我們將新增一個按鈕,如下所示。

<Button 
   android:id = "@+id/MyButton" 
   android:layout_width = "fill_parent" 
   android:layout_height = "wrap_content" 
   android:text = "@string/ButtonClick" /> 

新增按鈕後,我們的完整程式碼如下所示:

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
   <TextView 
      android:text = "@string/HelloXamarin" 
      android:textAppearance = "?android:attr/textAppearanceLarge" 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/textView2" /> 
    
   <Button 
      android:id = "@+id/MyButton" 
      android:layout_width = "fill_parent" 
      android:layout_height = "wrap_content" 
      android:text = "@string/ButtonClick" /> 
</LinearLayout>

接下來,我們在strings.xml檔案中註冊我們的按鈕值。

<string name = "ButtonClick">Click Me!</string>

strings.xml檔案中新增按鈕後,我們將開啟MainActivity.cs檔案,為單擊按鈕新增操作,如下面的程式碼所示。

using System; 
using Android.App; 
using Android.Content; 
using Android.Runtime; 
using Android.Views; 
using Android.Widget; 
using Android.OS;  

namespace HelloXamarin {     
   [Activity(Label = "HelloXamarin", MainLauncher = true, Icon = "@drawable/icon")] 
   public class MainActivity : Activity { 
      protected override void OnCreate(Bundle bundle) { 
         base.OnCreate(bundle); 
         SetContentView(Resource.Layout.Main); 
         Button button = FindViewById<Button>(Resource.Id.MyButton); 
         button.Click += delegate { button.Text = "Hello world I am your first App"; }; 
      } 
   } 
} 

接下來,構建並執行您的應用程式。

Run the application

單擊按鈕後,您將獲得以下輸出:

Output

Xamarin - 應用程式清單

所有 Android 應用程式都具有一個清單檔案,通常稱為AndroidManifest.xml。清單檔案包含 Android 平臺的應用程式成功執行所需的一切。

在這裡,我們列出了一些清單檔案的重要功能:

  • 它宣告應用程式所需的最低 API 級別

  • 它宣告應用程式所需的許可權,例如相機、位置等。

  • 它授予應用程式使用或需要的硬體和軟體功能的許可權。

  • 它列出必須連結的庫。

以下螢幕截圖顯示了一個清單檔案。

Andriod Manifest

應用程式名稱 - 指的是您的應用程式的標題

包名稱 - 用於標識您的應用程式的唯一名稱。

應用程式圖示 - 是在您的應用程式的 Android 主螢幕上顯示的圖示。

版本號 - 用於顯示您的應用程式的一個版本比另一個版本更新的單個數字。

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
   android:versionCode="1" > 

版本名稱 - 是您的應用程式的使用者友好版本字串,使用者將在您的應用程式設定和 Google Play 商店中看到。以下程式碼顯示了版本名稱的示例。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"     
   android:versionName="1.0.0"> 

最低 Android 版本 - 您的應用程式支援的最低 Android 版本平臺。

<uses-sdk android:minSdkVersion="16" /> 

在上面的示例中,我們的最低 Android 版本是 API 級別 16,通常稱為JELLY BEAN

目標 Android 版本 - 您的應用程式針對其進行編譯的 Android 版本。

Xamarin - Android 資源

建立新的 Android 專案時,預設情況下會向專案新增一些檔案。我們將這些預設專案檔案和資料夾稱為Android 資源。請檢視以下螢幕截圖。

Android Resources

預設 Android 資源包括以下內容:

  • AndroidManifest.xml 檔案 - 包含有關您的 Android 應用程式的資訊,例如應用程式名稱、許可權等。

  • 資原始檔夾 - 資源可以是影像、佈局、字串等,可以透過 Android 的資源系統載入。

  • Resources/drawable 資料夾 - 儲存您將在應用程式中使用的所有影像。

  • Resources/layout 資料夾 - 包含 Android 用於構建使用者介面的所有 Android XML 檔案 (.axml)。

  • Resources/values 資料夾 - 包含 XML 檔案,用於宣告整個應用程式中的字串(和其他型別)的鍵值對。這就是通常在 Android 上設定多種語言的本地化的方式。

  • Resources.designer.cs - 建立 Android 專案時會自動建立此檔案,其中包含引用 Android 資源的唯一識別符號。

  • MainActivity.cs 檔案 - 這是您的 Android 應用程式的第一個活動,也是從那裡啟動主要應用程式操作的地方。

可以透過儲存在resources.designer.cs檔案中的唯一 ID以程式設計方式訪問資原始檔。ID 包含在一個名為Resource的類中。新增到專案的任何資源都會自動生成在resource 類中。

以下程式碼顯示如何建立一個包含七張影像的 gridview 專案:

namespace HelloGridView { 
   [System.CodeDom.Compiler.GeneratedCodeAttribute
      ("Xamarin.Android.Build.Tas ks", 
      "1.0.0.0")] 
   public partial class Resource { 
      static Resource() {     
         global::Android.Runtime.ResourceIdManager.UpdateIdValues(); 
      } 
   
      public static void UpdateIdValues() {} 
      public partial class Attribute { 
         static Attribute() { 
            global::Android.Runtime.ResourceIdManager.UpdateIdValues(); 
         } 
   
         private Attribute() {} 
      } 
      
      public partial class Drawable { 
         // aapt resource value: 0x7f020000 
         public const int Icon = 2130837504; 
    
         // aapt resource value: 0x7f020001 
         public const int img1 = 2130837505; 
    
         // aapt resource value: 0x7f020002 
         public const int img2 = 2130837506;
         
         // aapt resource value: 0x7f020003 
         public const int img3 = 2130837507; 
    
         // aapt resource value: 0x7f020004 
         public const int img4 = 2130837508; 
    
         // aapt resource value: 0x7f020005 
         public const int img5 = 2130837509; 
    
         // aapt resource value: 0x7f020006 
         public const int img6 = 2130837510; 
    
         // aapt resource value: 0x7f020007 
         public const int img7 = 2130837511; 
    
         static Drawable() { 
            global::Android.Runtime.ResourceIdManager.UpdateIdValues(); 
         } 
   
         private Drawable() {} 
      } 
   
      public partial class Id { 
         // aapt resource value: 0x7f050000 
         public const int gridview = 2131034112; 
    
         static Id() { 
            global::Android.Runtime.ResourceIdManager.UpdateIdValues(); 
         } 
   
         private Id() {} 
      } 
   
      public partial class Layout { 
         // aapt resource value: 0x7f030000 
         public const int Main = 2130903040;
         static Layout() { 
            global::Android.Runtime.ResourceIdManager.UpdateIdValues(); 
         } 
         private Layout() {} 
      } 
   
      public partial class String { 
         // aapt resource value: 0x7f040001 
         public const int ApplicationName = 2130968577; 
    
         // aapt resource value: 0x7f040000 
         public const int Hello = 2130968576; 
    
         static String() { 
            global::Android.Runtime.ResourceIdManager.UpdateIdValues(); 
         } 
         private String() {} 
      } 
   } 
}   

從上面的程式碼中,七張影像在一個名為drawable的類中引用。這些影像是以程式設計方式新增的。如果使用者向專案新增另一張影像,它也將新增到drawable類中。專案中包含的gridview也會被新增並存儲在它自己的類中。資原始檔夾中包含的每個專案都會自動生成並存儲在一個類中。

Xamarin - Android 活動生命週期

當用戶瀏覽 Android 應用程式時,會發生一系列事件。例如,當用戶啟動應用程式(例如 Facebook 應用程式)時,它會啟動並對使用者在前景中可見,onCreate() → onStart() → onResume()

如果啟動另一個活動(例如,來電),則 Facebook 應用程式將轉到後臺,並且來電轉到前景。我們現在有兩個正在執行的程序。

onPause()  --- > onStop()

電話結束後,Facebook 應用程式返回前景。將呼叫三種方法。

onRestart() --- > onStart() --- > onResume()

Android 活動中有 7 個生命週期程序。它們包括:

  • onCreate - 在第一次建立活動時呼叫。

  • onStart - 當活動啟動並對使用者可見時呼叫。

  • onResume - 當活動開始與使用者互動時呼叫。使用者輸入在此階段發生。

  • onPause - 當活動在後臺執行但尚未被殺死時呼叫。

  • onStop - 當活動不再對使用者可見時呼叫。

  • onRestart - 在活動停止後、再次啟動之前呼叫。當用戶返回到已停止的先前活動時,通常會呼叫它。

  • onDestroy - 這是在活動從記憶體中刪除之前的最後一次呼叫。

下圖顯示了 Android 活動生命週期:

Android Activity Lifecycle

Xamarin - 許可權

在 Android 中,預設情況下,沒有任何應用程式具有執行任何會影響使用者或作業系統的操作的許可權。為了讓應用程式執行任務,它必須宣告許可權。在 Android 系統授予許可權之前,應用程式無法執行該任務。這種許可權機制阻止應用程式在未經使用者同意的情況下隨意操作。

許可權需要記錄在AndroidManifest.xml檔案中。要新增許可權,我們雙擊屬性,然後轉到 Android Man...必需許可權將出現。選中您希望新增的相應許可權。

Access Checkin Properties

相機 - 它提供訪問裝置相機的許可權。

<uses-permission android:name="android.permission.CAMERA" />

網際網路 − 提供訪問網路資源。

<uses-permission android:name="android.permission.INTERNET" /> 

讀取聯絡人 − 提供讀取裝置上聯絡人的許可權。

<uses-permission android:name="android.permission.READ_CONTACTS" /> 

讀取外部儲存 − 提供讀取和儲存外部儲存資料。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

日曆 − 允許應用訪問使用者裝置上的日曆和事件。此許可權可能很危險,因為它允許應用在所有者不知情的情況下向來賓傳送電子郵件。新增此許可權的語法如下所示:

<uses-permission android:name="android.permission-group.CALENADAR" /> 

簡訊 − 擁有此許可權的應用可以訪問裝置的訊息服務。包括讀取、寫入和編輯簡訊和彩信。其語法如下所示。

<uses-permission android:name="android.permission-group.SMS" />

位置 − 擁有此許可權的應用可以使用 GPS 網路訪問裝置的位置。

<uses-permission android:name="android.permission-group.LOCATION" /> 

藍牙 − 擁有此許可權的應用可以與其他支援藍牙的裝置無線交換資料檔案。

<uses-permission android:name="android.permission.BLUETOOTH" />

Xamarin - 構建應用程式 GUI

TextView

TextView 是 Android 控制元件中非常重要的元件。它主要用於在 Android 螢幕上顯示文字。

要建立一個 TextView,只需開啟main.axml並在線性佈局標籤之間新增以下程式碼。

<TextView 
   android:text = "Hello I am a text View" 
   android:layout_width = "match_parent" 
   android:layout_height = "wrap_content" 
   android:id = "@+id/textview1" /> 

按鈕

按鈕是一個控制元件,用於在單擊時觸發事件。在您的Main.axml檔案中,鍵入以下程式碼以建立按鈕。

<Button 
   android:id = "@+id/MyButton" 
   android:layout_width = "fill_parent" 
   android:layout_height = "wrap_content" 
   android:text = "@string/Hello" />

開啟Resources\Values\Strings.xml,並在``標籤之間鍵入以下程式碼行。

<string name="Hello">Click Me!</string>

以上程式碼提供了我們建立的按鈕的值。接下來,我們開啟MainActivity.cs並建立單擊按鈕時要執行的操作。在base.OnCreate (bundle) 方法下鍵入以下程式碼。

Button button = FindViewById<Button>(Resource.Id.MyButton); 
button.Click += delegate { button.Text = "You clicked me"; };
Button App

以上程式碼在使用者單擊按鈕時顯示“您點選了我”。

FindViewById<< --> 此方法查詢已識別的檢視的 ID。它在 .axml 佈局檔案中搜索 ID。

FindViewById

複選框

當需要從一組選項中選擇多個選項時,使用複選框。在此示例中,我們將建立一個複選框,選中時顯示已選中訊息,否則顯示未選中。

首先,我們開啟專案中的Main.axml檔案,並鍵入以下程式碼行以建立複選框。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:background = "#d3d3d3" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
   <CheckBox 
      android:text = "CheckBox" 
      android:padding = "25dp" 
      android:layout_width = "300dp" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/checkBox1" 
      android:textColor = "@android:color/black" 
      android:background = "@android:color/holo_blue_dark" /> 
</LinearLayout> 

接下來,轉到MainActivity.cs新增功能程式碼。

CheckBox checkMe = FindViewById<CheckBox>(Resource.Id.checkBox1); 
checkMe.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { 
   CheckBox check = (CheckBox)sender; 
   if(check.Checked) { 
      check.Text = "Checkbox has been checked"; 
   } else { 
      check.Text = "Checkbox has not been checked"; 
   } 
};

在上面的程式碼中,我們首先使用findViewById查詢複選框。接下來,我們為複選框建立一個處理程式方法,並在處理程式中建立一個 if else 語句,根據選擇的輸出顯示訊息。

CompoundButton.CheckedChangeEventArgs → 此方法在複選框狀態更改時觸發事件。

Checkbox has been checked

進度條

進度條是用於顯示操作進度的控制元件。要新增進度條,請在Main.axml檔案中新增以下程式碼行。

<ProgressBar 
   style="?android:attr/progressBarStyleHorizontal" 
   android:layout_width = "match_parent" 
   android:layout_height = "wrap_content" 
   android:id = "@+id/progressBar1" />

接下來,轉到MainActivity.cs並設定進度條的值。

ProgressBar pb = FindViewById<ProgressBar>(Resource.Id.progressBar1); 
pb.Progress = 35;

在上面的程式碼中,我們建立了一個值為 35 的進度條。

單選按鈕

這是一個 Android 控制元件,允許使用者從一組選項中選擇一個。在本節中,我們將建立一個包含汽車列表的單選組,該組將檢索選中的單選按鈕。

首先,我們新增一個單選組和一個textview,如下面的程式碼所示:

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:background = "@android:color/darker_gray" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
   <TextView 
      android:text = "What is your favourite Car" 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/textView1" 
      android:textColor = "@android:color/black" /> 
   <RadioGroup 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/radioGroup1" 
      android:backgroundTint = "#a52a2aff" 
      android:background = "@android:color/holo_green_dark"> 
   <RadioButton 
      android:layout_width = "wrap_content" 
      android:layout_height = "wrap_content" 
      android:text = "Ferrari" 
      android:id = "@+id/radioFerrari" /> 
   <RadioButton 
      android:layout_width = "wrap_content" 
      android:layout_height = "wrap_content" 
      android:text = "Mercedes" 
      android:id = "@+id/radioMercedes" /> 
   <RadioButton 
      android:layout_width = "wrap_content" 
      android:layout_height = "wrap_content" 
      android:text = "Lamborghini" 
      android:id = "@+id/radioLamborghini" />
   <RadioButton 
      android:text = "Audi" 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/radioAudi" /> 
   </RadioGroup> 
</LinearLayout>             

要執行操作,當單擊單選按鈕時,我們新增一個活動。轉到MainActivity.cs並建立一個新的事件處理程式,如下所示。

private void onClickRadioButton(object sender, EventArgs e) { 
   RadioButton cars = (RadioButton)sender; 
   Toast.MakeText(this, cars.Text, ToastLength.Short).Show 
   (); 
} 

Toast.MakeText() → 這是一種檢視方法,用於在一個小的彈出視窗中顯示訊息/輸出。在OnCreate()方法的底部,就在SetContentView()之後,新增以下程式碼段。這將捕獲每個單選按鈕並將它們新增到我們建立的事件處理程式中。

RadioButton radio_Ferrari = FindViewById<RadioButton> 
   (Resource.Id.radioFerrari); 
   RadioButton radio_Mercedes = FindViewById<RadioButton> 
   (Resource.Id.radioMercedes); 
   RadioButton radio_Lambo = FindViewById<RadioButton> 
   (Resource.Id.radioLamborghini); 
   RadioButton radio_Audi = FindViewById<RadioButton> 
   (Resource.Id.radioAudi); 
   radio_Ferrari.Click += onClickRadioButton; 
   radio_Mercedes.Click += onClickRadioButton; 
   radio_Lambo.Click += onClickRadioButton; 
   radio_Audi.Click += onClickRadioButton; 

現在,執行您的應用程式。它應該顯示以下螢幕作為輸出:

Output Displayed

開關按鈕

開關按鈕用於在兩種狀態之間切換,例如,它可以在開啟和關閉之間切換。開啟Resources\layout\Main.axml並新增以下程式碼行以建立開關按鈕。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:background = "#d3d3d3" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
   <ToggleButton 
      android:id = "@+id/togglebutton" 
      android:layout_width = "wrap_content" 
      android:layout_height = "wrap_content" 
      android:textOn = "Torch ON" 
      android:textOff = "Torch OFF" 
      android:textColor = "@android:color/black" /> 
</LinearLayout>

單擊開關欄時,我們可以向其中新增操作。開啟MainActivity.cs並在OnCreate()方法類之後新增以下程式碼行。

ToggleButton togglebutton = FindViewById<ToggleButton> (Resource.Id.togglebutton); 
togglebutton.Click += (o, e) => { 
   if (togglebutton.Checked) 
      Toast.MakeText(this, "Torch is ON", ToastLength.Short).Show (); 
   else 
      Toast.MakeText(this, "Torch is OFF", 
      ToastLength.Short).Show(); 
}; 

現在,當您執行應用程式時,它應該顯示以下輸出:

Torch ON and OFF

評分條

評分條是由星組成的表單元素,應用程式使用者可以使用它來評價您為他們提供的專案。在您的Main.axml檔案中,建立一個包含 5 顆星的新評分條。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:background = "#d3d3d3" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
   <RatingBar 
      android:layout_width = "wrap_content" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/ratingBar1" 
      android:numStars = "5" 
      android:stepSize = "1.0" /> 
</LinearLayout> 

執行應用程式後,它應該顯示以下輸出:

RatingBarApp

自動完成 TextView

這是一個 TextView,在使用者鍵入時顯示完整建議。我們將建立一個包含人員姓名列表的自動完成 TextView,以及一個按鈕,單擊該按鈕將顯示從 TextView 輸入的所選名稱。

開啟Main.axml並編寫以下程式碼。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:layout_width = "fill_parent" 
   android:background = "#d3d3d3" 
   android:layout_height = "fill_parent"> 
   <TextView 
      android:text = "Enter Name" 
      android:textAppearance = "?android:attr/textAppearanceMedium" 
      android:layout_width = "fill_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/textView1" 
      android:padding = "5dp" 
      android:textColor = "@android:color/black" /> 
   <AutoCompleteTextView 
      android:layout_width = "fill_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/autoComplete1" 
      android:textColor = "@android:color/black" /> 
   <Button 
      android:text = "Submit" 
      android:layout_width = "fill_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/btn_Submit" 
      android:background="@android:color/holo_green_dark" /> 
</LinearLayout>

上面的程式碼生成一個用於鍵入的 TextView、一個用於顯示建議的AutoCompleteTextView和一個用於顯示從 TextView 輸入的名稱的按鈕。轉到MainActivity.cs新增功能。

建立一個新的事件處理程式方法,如下所示。

protected void ClickedBtnSubmit(object sender, System.EventArgs e){ 
   if (autoComplete1.Text != ""){ 
      Toast.MakeText(this, "The Name Entered =" 
         + autoComplete1.Text, ToastLength.Short).Show(); 
   } else { 
      Toast.MakeText(this, "Enter a Name!", ToastLength.Short).Show(); 
   } 
} 

建立的處理程式檢查自動完成 TextView 是否為空。如果它不為空,則顯示選定的自動完成文字。在OnCreate()類中鍵入以下程式碼。

autoComplete1 = FindViewById<AutoCompleteTextView>(Resource.Id.autoComplete1); 
btn_Submit = FindViewById<Button>(Resource.Id.btn_Submit);  
var names = new string[] { "John", "Peter", "Jane", "Britney" }; 
ArrayAdapter adapter = new ArrayAdapter<string>(this,           
   Android.Resource.Layout.SimpleSpinnerItem, names); 
autoComplete1.Adapter = adapter; 
btn_Submit.Click += ClickedBtnSubmit; 

ArrayAdapter − 這是一種集合處理程式,它從列表集合中讀取資料項並將其作為檢視返回或在螢幕上顯示它們。

現在,執行應用程式時,它應該顯示以下輸出。

AutoComplete TextView

Xamarin - 選單

彈出選單

彈出選單是指附加到檢視的選單;它也稱為快捷選單。讓我們看看如何將彈出選單新增到 Android 應用程式。

建立一個新專案並將其命名為popUpMenu App。開啟Main.axml並建立一個按鈕,該按鈕將用於顯示彈出選單。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:background = "#d3d3d3" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
   <Button 
      android:id = "@+id/popupButton" 
      android:layout_width = "fill_parent" 
      android:layout_height = "wrap_content" 
      android:text = "Show popup menu" 
      android:background = "@android:color/holo_green_dark" 
      android:textColor = "@android:color/black" /> 
</LinearLayout>

Resources資料夾下建立一個新資料夾,並將其命名為Menu。在 Menu 資料夾中,新增一個名為popMenu.xml的新 xml 檔案。

popMenu.xml下,新增以下選單項。

<?xml version = "1.0" encoding="utf-8"?> 
<menu xmlns:android = "http://schemas.android.com/apk/res/android"> 
   <item 
      android:id = "@+id/file_settings" 
      android:icon = "@drawable/img_settings" 
      android:title = "Settings" 
      android:showAsAction = "ifRoom"> 
     
      <item 
         android:id = "@+id/new_game1" 
         android:icon = "@drawable/imgNew" 
         android:title = "New File Settings"/> 
      <item 
         android:id = "@+id/help" 
         android:icon = "@drawable/img_help" 
         android:title = "Help" /> 
      <item 
         android:id = "@+id/about_app" 
         android:icon = "@drawable/img_help" 
         android:title = "About app"/> 
   </item> 
</menu>  

新增選單項後,轉到mainActivity.cs以在單擊按鈕時顯示彈出選單。

protected override void OnCreate(Bundle bundle) { 
   base.OnCreate(bundle); 
   SetContentView(Resource.Layout.Main); 
   Button showPopupMenu = FindViewById<Button>(Resource.Id.popupButton); 
   showPopupMenu.Click += (s, arg) => { 
      PopupMenu menu = new PopupMenu(this, showPopupMenu); 
      menu.Inflate(Resource.Menu.popMenu); 
      menu.Show(); 
   }; 
} 

現在,構建並執行您的應用程式。它應該產生以下輸出:

Show Popup Menu

選項選單

選項選單是應用程式的主要選單集合,主要用於儲存設定、搜尋等。在這裡,我們將建立一個包含三個專案的設定選單,即新建檔案設定、幫助和關於應用程式

要建立選項選單,我們必須在資原始檔夾中建立一個新的 XML 佈局檔案。首先,我們將新增一個新的 XML 檔案。右鍵單擊Layout 資料夾,然後轉到新增→新建項→Visual C#→XML 檔案

佈局檔案選擇一個合適的名稱。在我們的示例中,我們將檔案命名為myMenu.xml

myMenu.xml中,我們將建立一個新選單並在其中新增專案。以下程式碼顯示瞭如何操作。

<?xml version = "1.0" encoding = "utf-8"?> 
<menu xmlns:android = "http://schemas.android.com/apk/res/android"> 
  <item 
      android:id = "@+id/file_settings" 
      android:icon = "@drawable/img_settings" 
      android:title = "Settings" 
      android:showAsAction = "ifRoom">
      
      <menu> 
         <item 
            android:id = "@+id/new_game1" 
            android:icon = "@drawable/imgNew" 
            android:title = "New File Settings" /> 
         <item 
            android:id = "@+id/help" 
            android:icon = "@drawable/img_help" 
            android:title = "Help" /> 
         <item 
            android:id = "@+id/about_app" 
            android:icon = "@drawable/img_help" 
            android:title = "About app"/> 
      </menu> 
   </item> 
</menu>

接下來,我們導航到MainActivity.cs併為onOptionsMenu()建立一個重寫類。

public override bool OnCreateOptionsMenu(IMenu menu) { 
   MenuInflater.Inflate(Resource.Menu.myMenu, menu); 
   return base.OnPrepareOptionsMenu(menu); 
}

接下來,我們建立一個操作來響應選擇設定選單時。為此,我們為OnOptionsItemSelected()選單建立另一個重寫類。

public override bool OnOptionsItemSelected(IMenuItem item) { 
   if (item.ItemId == Resource.Id.file_settings) { 
      // do something here... 
      return true;  
   } 
   return base.OnOptionsItemSelected(item); 
} 

我們的最終完整程式碼如下所示:

namespace optionsMenuApp {     
   [Activity(Label = "options Menu", MainLauncher = true, Icon = "@drawable/icon")] 
   public class MainActivity : Activity { 
      public override bool OnCreateOptionsMenu(IMenu menu) { 
         MenuInflater.Inflate(Resource.Menu.myMenu, menu); 
         return base.OnPrepareOptionsMenu(menu); 
      } 
      public override bool OnOptionsItemSelected(IMenuItem item) { 
         if (item.ItemId == Resource.Id.file_settings) { 
            // do something here... 
            return true;  
         } 
         return base.OnOptionsItemSelected(item); 
      } 
   } 
} 

現在,構建並執行您的應用程式。它應該產生以下輸出:

New File settings

Xamarin - 佈局

線性佈局

線上性佈局中,內容以水平或垂直方式排列。

線性佈局─水平

此佈局的內容水平排列。在此演示中,我們將建立 3 個按鈕,並將它們水平排列線上性佈局中。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "horizontal" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent" 
   android:background = "#d3d3d3" 
   android:minWidth="25px" 
   android:minHeight="25px"> 
   <Button 
      android:id="@+id/MyButton1" 
      android:layout_width="wrap_content" 
      android:layout_margin="10dp" 
      android:layout_height="wrap_content" 
      android:text="Button 1" 
      android:background="@android:color/holo_green_dark" /> 
   <Button 
      android:id="@+id/MyButton2" 
      android:layout_width="wrap_content" 
      android:layout_margin="10dp" 
      android:layout_height="wrap_content" 
      android:text="Button 2" 
      android:background="@android:color/holo_green_dark" /> 
   <Button 
      android:id="@+id/MyButton3" 
      android:layout_width="wrap_content" 
      android:layout_margin="10dp"
      android:layout_height="wrap_content" 
      android:text="Button 3" 
      android:background="@android:color/holo_green_dark" /> 
</LinearLayout>         

結果輸出如下所示:

Linear Layout Horizontal

線性佈局─垂直

這種型別的佈局以垂直方式放置子檢視。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent" 
   android:background = "#d3d3d3" 
   android:minWidth = "25px" 
   android:minHeight = "25px"> 
   <Button 
      android:id = "@+id/MyButton1" 
      android:layout_width = "fill_parent" 
      android:layout_margin = "10dp"
      android:layout_height = "wrap_content" 
      android:text = "Button 1" 
      android:background = "@android:color/holo_green_dark" /> 
   <Button 
      android:id = "@+id/MyButton2" 
      android:layout_width = "fill_parent" 
      android:layout_margin = "10dp" 
      android:layout_height = "wrap_content" 
      android:text = "Button 2" 
      android:background = "@android:color/holo_green_dark" /> 
   <Button 
      android:id = "@+id/MyButton3" 
      android:layout_width = "fill_parent" 
      android:layout_margin = "10dp" 
      android:layout_height = "wrap_content" 
      android:text="Button 3" 
      android:background = "@android:color/holo_green_dark" /> 
</LinearLayout> 

其結果輸出如下:

Linear layout Vertical

相對佈局

在此檢視中,子檢視的位置相對於其父檢視或其同級檢視。在下面的示例中,我們將建立 3 個 EditText 檢視和一個按鈕,然後相對地對齊它們。

建立一個新專案並將其命名為relative layout app。開啟main.axml並新增以下程式碼。

<?xml version = "1.0" encoding = "utf-8"?> 
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:layout_width = "match_parent" 
   android:layout_height = "match_parent" 
   android:paddingLeft = "16dp" 
   android:background = "#d3d3d3" 
   android:paddingRight = "16dp"> 
   <EditText 
      android:id = "@+id/name" 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:hint = "First Name" 
      android:textColorHint = "@android:color/background_dark" 
      android:textColor = "@android:color/background_dark" /> 
   <EditText 
      android:id = "@+id/lastName" 
      android:layout_width = "0dp" 
      android:layout_height = "wrap_content" 
      android:hint = "Last Name" 
      android:layout_below = "@id/name" 
      android:textColorHint = "@android:color/background_dark" 
      android:textColor = "@android:color/background_dark" 
      android:layout_alignParentLeft = "true" 
      android:layout_toLeftOf = "@+id/age" /> 
   <EditText 
      android:id = "@id/age" 
      android:layout_width = "80dp" 
      android:layout_height = "wrap_content" 
      android:layout_below = "@id/name" 
      android:hint = "Age" 
      android:textColorHint = "@android:color/background_dark"
      android:textColor = "@android:color/background_dark" 
      android:layout_alignParentRight = "true" /> 
   <Button 
      android:layout_width = "85dp" 
      android:layout_height = "wrap_content" 
      android:layout_below = "@id/age" 
      android:layout_alignParentRight = "true" 
      android:text = "Submit" 
      android:background = "@android:color/holo_green_dark" /> 
</RelativeLayout> 

我們在本程式碼中使用的重要引數是:

  • android:layout_below − 將子檢視元素與其父元素對齊。

  • android:layout_alignParentLeft − 將父元素與左側對齊。

  • android:layout_toLeftOf − 此屬性將元素與另一個元素的左側對齊。

  • android:layout_alignParentRight − 將父元素與右側對齊。

現在構建並執行應用程式時,它將產生以下輸出螢幕:

Relative Layout

框架佈局

框架佈局用於僅顯示一個專案。很難在此佈局中排列多個專案而不會使它們相互重疊。

啟動一個新專案並將其命名為frameLayoutApp。建立一個新的框架佈局,如下所示。

<?xml version = "1.0" encoding = "utf-8"?> 
<FrameLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
  <ImageView 
      android:id = "@+id/ImageView1" 
      android:scaleType = "matrix" 
      android:layout_height = "fill_parent" 
      android:layout_width = "fill_parent" 
      android:src = "@drawable/img1" /> 
   <TextView 
      android:layout_width = "fill_parent" 
      android:layout_height = "wrap_content" 
      android:textSize = "50dp" 
      android:textColor = "#000" 
      android:text = "This is a Lake" /> 
   <TextView 
      android:gravity = "right" 
      android:layout_width = "fill_parent" 
      android:layout_height = "wrap_content" 
      android:textSize = "50dp" 
      android:text = "A very Deep Lake" 
      android:layout_gravity = "bottom" 
      android:textColor = "#fff" /> 
</FrameLayout>

上面的程式碼建立了一個imageView,它填充了整個螢幕。然後,兩個 TextView 浮在imageView上方。

現在,構建並執行您的應用程式。它將顯示以下輸出:

Frame layout

表格佈局

在此佈局中,檢視被排列成。讓我們看看它是如何工作的。

<?xml version = "1.0" encoding = "utf-8"?> 
<TableLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:layout_width = "fill_parent" 
   android:background = "#d3d3d3" 
   android:layout_height = "fill_parent" 
   android:stretchColumns = "1"> 
   
   <TableRow> 
      <TextView 
         android:text = "First Name:" 
         android:layout_width = "wrap_content" 
         android:layout_height = "wrap_content" 
         android:textColor = "@android:color/black" /> 
      <EditText 
         android:width = "100px" 
         android:layout_width = "fill_parent" 
         android:layout_height = "30dp"
         android:textColor = "@android:color/black" /> 
   </TableRow> 
   
   <TableRow> 
      <TextView 
         android:text = "Last Name:" 
         android:layout_width = "wrap_content" 
         android:layout_height = "wrap_content" 
         android:textColor = "@android:color/black" /> 
      <EditText 
         android:width = "50px" 
         android:layout_width = "fill_parent" 
         android:layout_height = "30dp" 
         android:textColor = "@android:color/black" /> 
   </TableRow> 
   
   <TableRow> 
      <TextView 
         android:text = "Residence:" 
         android:layout_width = "wrap_content" 
         android:layout_height = "wrap_content" 
         android:textColor = "@android:color/black" /> 
      <EditText 
         android:width = "100px" 
         android:layout_width = "fill_parent" 
         android:layout_height = "30dp" 
         android:textColor = "@android:color/black" /> 
   </TableRow> 
   
   <TableRow> 
      <TextView 
         android:text = "Occupation:" 
         android:layout_width = "wrap_content" 
         android:layout_height = "wrap_content" 
         android:textColor = "@android:color/black" /> 
      <EditText 
         android:width = "100px" 
         android:layout_width = "fill_parent" 
         android:layout_height = "30dp" 
         android:textColor = "@android:color/black" /> 
   </TableRow> 
   
   <TableRow>
      <Button 
         android:text = "Cancel" 
         android:layout_width = "wrap_content" 
         android:layout_margin = "10dp" 
         android:layout_height = "wrap_content" 
         android:background = "@android:color/holo_green_dark" /> 
      <Button 
         android:text = "Submit" 
         android:width = "100px" 
         android:layout_margin = "10dp" 
         android:layout_width = "wrap_content" 
         android:layout_height = "wrap_content" 
         android:background = "@android:color/holo_green_dark" /> 
   </TableRow> 
</TableLayout>     

上面的程式碼建立了一個使用表格排列的簡單資料輸入表單。

Table Layout

Xamarin - Android 控制元件

日期選擇器

這是一個用於顯示日期的小部件。在此示例中,我們將建立一個日期選擇器,該選擇器在 TextView 上顯示設定的日期。

首先,建立一個新專案並將其命名為datePickerExample。開啟Main.axml並建立一個datepickertextview和一個button

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
   <DatePicker 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/datePicker1" /> 
   <TextView 
      android:text = "Current Date" 
      android:textAppearance = "?android:attr/textAppearanceLarge" 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/txtShowDate" /> 
   <Button 
      android:text = "Select Date" 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/btnSetDate" /> 
</LinearLayout> 

接下來,轉到Mainactivity.cs。我們首先在mainActivity:Activity類中建立一個 TextView 的私有例項。

該例項將用於儲存選定的日期或預設日期。

private TextView showCurrentDate;

接下來,在setContentView()方法之後新增以下程式碼。

DatePicker pickDate = FindViewById<DatePicker>(Resource.Id.datePicker1); 
showCurrentDate = FindViewById<TextView>(Resource.Id.txtShowDate); 
setCurrentDate(); 
Button button = FindViewById<Button>(Resource.Id.btnSetDate); 
button.Click += delegate { 
   showCurrentDate.Text = String.Format("{0}/{1}/{2}", 
      pickDate.Month, pickDate.DayOfMonth, pickDate.Year); 
}; 

在上面的程式碼中,我們透過使用FindViewById類從我們的main.axml檔案中查詢它們來引用我們的日期選擇器、TextView 和按鈕。

引用後,我們設定按鈕單擊事件,該事件負責將從日期選擇器選擇的日期傳遞到 TextView。

接下來,我們建立setCurrentDate()方法以將預設當前日期顯示到我們的 TextView。以下程式碼解釋了它是如何完成的。

private void setCurrentDate() { 
   string TodaysDate = string.Format("{0}", 
      DateTime.Now.ToString("M/d/yyyy").PadLeft(2, '0')); 
   showCurrentDate.Text = TodaysDate; 
} 

DateTime.Now.ToString()類將今天的日期時間繫結到字串物件。

現在,構建並執行應用程式。它應該顯示以下輸出:

DatePicker

時間選擇器

時間選擇器是一個用於顯示時間的小部件,還允許使用者選擇和設定時間。我們將建立一個基本的時間選擇器應用程式,它顯示時間並允許使用者更改時間。

轉到main.axml並新增一個新的按鈕、TextView 和一個時間選擇器,如下面的程式碼所示。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:background = "#d3d3d3" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
   <TimePicker 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/timePicker1" /> 
   <TextView
      android:text = "Time" 
      android:textAppearance = "?android:attr/textAppearanceLarge" 
      android:layout_width = "match_parent" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/txt_showTime" 
      android:textColor = "@android:color/black" /> 
   <Button 
      android:text = "Set Time" 
      android:layout_width = "200dp" 
      android:layout_height = "wrap_content" 
      android:id = "@+id/btnSetTime" 
      android:textColor = "@android:color/black" 
      android:background = "@android:color/holo_green_dark" /> 
</LinearLayout> 

轉到MainActivity.cs以新增在建立的 TextView 上顯示設定日期的功能。

public class MainActivity : Activity { 
   
   private TextView showCurrentTime; 
   
   protected override void OnCreate(Bundle bundle) { 
      
      base.OnCreate(bundle); 
      SetContentView(Resource.Layout.Main); 
      TimePicker Tpicker = FindViewById<TimePicker>(Resource.Id.timePicker1); 
      showCurrentTime = FindViewById<TextView>(Resource.Id.txt_showTime); 
      setCurrentTime(); 
      Button button = FindViewById<Button>(Resource.Id.btnSetTime); 
      
      button.Click += delegate { 
         showCurrentTime.Text = String.Format("{0}:{1}", 
            Tpicker.CurrentHour, Tpicker.CurrentMinute); 
      }; 
   } 
   private void setCurrentTime() { 
      string time = string.Format("{0}", 
         DateTime.Now.ToString("HH:mm").PadLeft(2, '0')); 
      showCurrentTime.Text = time;
   } 
} 

在上面的程式碼中,我們首先透過FindViewById<>類引用timepicker設定時間按鈕和用於顯示時間的 TextView。然後,我們為“設定時間”按鈕建立了一個單擊事件,該事件在單擊時將時間設定為使用者選擇的時間。預設情況下,它顯示當前系統時間。

setCurrentTime()方法類初始化txt_showTime TextView 以顯示當前時間。

現在,構建並執行您的應用程式。它應該顯示以下輸出:

Time Picker

微調框

微調框是一個用於從一組選項中選擇一個選項的小部件。它相當於下拉列表/組合框。首先,建立一個新專案並將其命名為Spinner App Tutorial

開啟layout資料夾下的Main.axml檔案,並建立一個新的spinner(下拉選單)。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent"> 
   <Spinner 
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content" 
      android:id = "@+id/spinner1" 
      android:prompt = "@string/daysOfWeek" /> 
</LinearLayout>       

開啟位於values資料夾下的Strings.xml檔案,並新增以下程式碼來建立spinner的選項。

<resources> 
  <string name = "daysOfWeek">Choose a planet</string> 
  <string-array name = "days_array"> 
      <item>Sunday</item> 
      <item>Monday</item> 
      <item>Tuesday</item> 
      <item>Wednesday</item> 
      <item>Thursday</item> 
      <item>Friday</item> 
      <item>Saturday</item> 
      <item>Sunday</item> 
   </string-array> 
</resources>

接下來,開啟MainActivity.cs檔案,新增顯示所選星期幾的功能。

protected override void OnCreate(Bundle bundle) { 
   base.OnCreate(bundle);  
   // Set our view from the "main" layout resource 
   SetContentView(Resource.Layout.Main); 
   Spinner spinnerDays = FindViewById<Spinner>(Resource.Id.spinner1); 
   spinnerDays.ItemSelected += new EventHandler
      <AdapterView.ItemSelectedEventArgs>(SelectedDay); 
   var adapter = ArrayAdapter.CreateFromResource(this, 
      Resource.Array.days_array, Android.Resource.Layout.SimpleSpinnerItem);  
   adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropD ownItem); 
   spinnerDays.Adapter = adapter; 
}  
private void SelectedDay(object sender, AdapterView.ItemSelectedEventArgs e) { 
   Spinner spinner = (Spinner)sender; 
   string toast = string.Format("The selected 
      day is {0}", spinner.GetItemAtPosition(e.Position)); 
   Toast.MakeText(this, toast, ToastLength.Long).Show(); 
} 

現在,構建並執行應用程式。它應該顯示以下輸出:

Spinner App

在上面的程式碼中,我們透過FindViewById<>類引用了在main.axml檔案中建立的spinner。然後,我們建立了一個新的arrayAdapter(),用於從strings.xml檔案中繫結我們的陣列項。

最後,我們建立了SelectedDay()方法,用於顯示所選的星期幾。

Xamarin - Android 對話方塊

警告對話方塊

在本節中,我們將建立一個按鈕,單擊該按鈕會顯示一個警告對話方塊。該對話方塊包含兩個按鈕,即刪除取消按鈕。

首先,轉到main.axml並在線性佈局內建立一個新的按鈕,如下面的程式碼所示。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:layout_width = "fill_parent" 
   android:background = "#d3d3d3" 
   android:layout_height = "fill_parent"> 
   <Button 
      android:id="@+id/MyButton" 
      android:layout_width = "fill_parent" 
      android:layout_height = "wrap_content" 
      android:text = "Click to Delete" 
      android:textColor = "@android:color/background_dark" 
      android:background = "@android:color/holo_green_dark" /> 
</LinearLayout>

接下來,開啟MainActivity.cs建立警告對話方塊並新增其功能。

protected override void OnCreate(Bundle bundle) { 
   base.OnCreate(bundle); 
   SetContentView(Resource.Layout.Main); 
   Button button = FindViewById<Button>(Resource.Id.MyButton); 
   button.Click += delegate { 
      AlertDialog.Builder alertDiag = new AlertDialog.Builder(this); 
      alertDiag.SetTitle("Confirm delete"); 
      alertDiag.SetMessage("Once deleted the move cannot be undone"); 
      alertDiag.SetPositiveButton("Delete", (senderAlert, args) => { 
         Toast.MakeText(this, "Deleted", ToastLength.Short).Show();
      }); 
      alertDiag.SetNegativeButton("Cancel", (senderAlert, args) => { 
         alertDiag.Dispose(); 
      }); 
      Dialog diag = alertDiag.Create(); 
      diag.Show(); 
   }; 
} 

完成後,構建並執行您的應用程式以檢視結果。

Confirm Delete

在上面的程式碼中,我們建立了一個名為alertDiag的警告對話方塊,其中包含以下兩個按鈕:

  • setPositiveButton - 它包含刪除按鈕操作,單擊該按鈕會顯示確認訊息已刪除

  • setNegativeButton - 它包含一個取消按鈕,單擊該按鈕會簡單地關閉警告對話方塊。

Xamarin - 相簿

Gallery是一種檢視型別,用於以水平可滾動列表顯示專案。然後在中心顯示所選專案。在此示例中,您將建立一個包含水平可滾動影像的Gallery。單擊影像將顯示所選影像的編號。

首先,建立一個新專案並命名它,例如Gallery App Tutorial。在開始編寫程式碼之前,將7張影像貼上到資源/drawable資料夾中。導航到資原始檔夾下的main.axml,並在線性佈局標籤之間新增一個Gallery。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
   android:orientation="vertical" 
   android:layout_width="fill_parent" 
   android:layout_height="fill_parent" 
   android:background="#d3d3d3"> 
   <Gallery 
      android:id="@+id/gallery" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:padding="10dp" /> 
</LinearLayout> 

建立一個名為ImageAdapter的新類。此類將用於將影像繫結到我們上面建立的Gallery。

第一步是新增一個包含上下文cont的類,我們用它來儲存欄位。

public class ImageAdapter : BaseAdapter { 
   Context cont; 
   public ImageAdapter(Context ct) { 
      cont = ct; 
   } 
}

接下來,我們計算包含影像的陣列列表並返回其大小。

public override int Count {  
   get {  
      return imageArraylist.Length;  
   }  
}

下一步,我們獲取專案的position。以下程式碼顯示瞭如何操作。

public override Java.Lang.Object GetItem(int position) { 
   return null; 
}  
public override long GetItemId(int position) { 
   return 0; 
} 

下一步,我們為介面卡引用的專案建立一個imageview

public override View GetView(int position,View convertView, ViewGroup parent) { 
   ImageView img = new ImageView(cont); 
   img.SetImageResource(imageArraylist[position]); 
   img.SetScaleType(ImageView.ScaleType.FitXy); 
   img.LayoutParameters = new Gallery.LayoutParams(200, 100); 
   return img; 
}

最後一步,我們建立對在resources.drawable資料夾中新增的影像的引用。為此,我們建立一個數組來儲存影像集合。以下程式碼解釋瞭如何操作。

int[] imageArraylist = { 
   Resource.Drawable.img1, 
   Resource.Drawable.img2, 
   Resource.Drawable.img3, 
   Resource.Drawable.img4, 
   Resource.Drawable.img5,
   Resource.Drawable.img6, 
  }; 
}   

接下來,我們轉到mainActivity.cs並在OnCreate()方法下插入以下程式碼。

Gallery myGallery = (Gallery)FindViewById<Gallery>(Resource.Id.gallery); 
myGallery.Adapter = new ImageAdapter(this); 
myGallery.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs args) { 
   Toast.MakeText(this, 
      args.Position.ToString(), ToastLength.Short).Show(); 
}

最後,構建並執行您的應用程式以檢視輸出。

Gallery

Xamarin - Android 檢視

ListViews

ListView是一個使用者介面元素,用於顯示可滾動的專案列表。

將資料繫結到ListViews

在此示例中,您將建立一個顯示星期幾的ListView。首先,讓我們建立一個新的XML檔案並將其命名為listViewTemplate.xml

listViewTemplate.xml中,我們新增一個新的textview,如下所示。

<?xml version = "1.0" encoding = "utf-8" ?> 
<TextView xmlns:android = "http://schemas.android.com/apk/res/android" 
android:id = "@+id/textItem"  
android:textSize ="20sp" 
android:layout_width = "fill_parent"  
android:layout_height = "wrap_content"/>

接下來,轉到Main.axml並在線性佈局內建立一個新的listview。

<ListView 
   android:minWidth="25px" 
   android:minHeight="25px" 
   android:layout_width="match_parent" 
   android:layout_height="match_parent" 
   android:id="@+id/listView1" />

開啟MainActivity.cs並鍵入以下程式碼以將資料繫結到我們建立的listview。程式碼必須寫在OnCreate()方法內。

SetContentView(Resource.Layout.Main); 
var listView = FindViewById<ListView>(Resource.Id.listView1); 
var data = new string[] { 
   "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" 
}; 
listView.Adapter = new ArrayAdapter(this, Resource.Layout.ListViewTemplate, data); 

Var data = new string[]只是將我們的專案作為陣列儲存。

陣列介面卡將集合中的專案作為檢視返回。預設情況下,陣列介面卡使用預設的textView來顯示每個專案。在上面的程式碼中,我們在ListViewTemplate.xml中建立了自己的textview,並使用如下所示的建構函式引用它。

ArrayAdapter(this, Resource.Layout.ListViewTemplate, data); 

最後,構建並執行您的應用程式以檢視輸出。

ListView App

GridViews

GridView是一個檢視組,允許應用程式以二維方式佈局內容,可滾動的網格。

要新增GridView,請建立一個新專案並將其命名為gridViewApp。轉到Main.axml並新增一個grid,如下所示。

<?xml version = "1.0" encoding="utf-8"?> 
<GridView xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:id = "@+id/gridview" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent" 
   android:columnWidth = "90dp" 
   android:numColumns = "auto_fit" 
   android:verticalSpacing = "10dp" 
   android:horizontalSpacing = "10dp" 
   android:stretchMode = "columnWidth" 
   android:gravity = "center" />

接下來,建立一個新類並將其命名為ImageAdpter.cs。此類將包含將顯示在網格中的所有專案的介面卡類。

ImageAdapter中,新增以下程式碼:

public class ImageAdapter : BaseAdapter { 
   Context context; 
   public ImageAdapter(Context ch) {  
      context = ch; 
   } 
      
   public override int Count { 
      get { 
         return cars.Length; 
      } 
   } 
      
   public override long GetItemId(int position) { 
   return 0; 
   } 
      
   public override Java.Lang.Object GetItem(int position) { 
      return null; 
   } 
      
   public override View GetView(int position, 
      View convertView, ViewGroup parent) { 
      ImageView imageView; 
      if (convertView == null) {   
         imageView = new ImageView(context); 
         imageView.LayoutParameters = new GridView.LayoutParams(100, 100); 
         imageView.SetScaleType(ImageView.ScaleType.CenterCrop); 
         imageView.SetPadding(8, 8, 8, 8); 
      } else { 
         imageView = (ImageView)convertView; 
      } 
             
      imageView.SetImageResource(cars[position]); 
      return imageView; 
   } 
   
   int[] cars = { 
      Resource.Drawable.img1, Resource.Drawable.img2, 
      Resource.Drawable.img3, Resource.Drawable.img4, 
      Resource.Drawable.img5, Resource.Drawable.img6, 
   }; 
}            

在上面的程式碼中,我們只是將我們的汽車影像繫結到影像介面卡。接下來,開啟MainActivity.cs並在setContentView()之後新增以下程式碼。

var gridview = FindViewById<GridView>(Resource.Id.gridview); 
gridview.Adapter = new ImageAdapter(this); 
gridview.ItemClick += delegate(object sender, 
   AdapterView.ItemClickEventArgs args) { 
      Toast.MakeText(this, 
         args.Position.ToString(), ToastLength.Short).Show(); 
};

上面的程式碼在main.axml中查詢GridView並將其繫結到imageAdapter類。Gridview.ItemClick建立一個onClick事件,當用戶單擊影像時,該事件會返回所選影像的位置。

現在,構建並執行您的應用程式以檢視輸出。

GridView

Xamarin - 多螢幕應用程式

在本章中,我們將建立一個登入系統,允許使用者註冊。然後,在成功登入後,我們將註冊使用者帶到應用程式的主螢幕。

首先,建立一個新專案並將其命名為Login System。在您的新專案中,轉到main.axml並新增兩個按鈕和一個進度條,如下所示。

<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:layout_width = "fill_parent" 
   android:layout_height = "fill_parent" 
   android:background = "@android:color/background_light" 
   android:weightSum = "100" 
   android:minWidth = "25px" 
   android:minHeight = "25px"> 
   <TextView 
      android:text = "Login App" 
      android:textAppearance = "?android:attr/textAppearanceMedium" 
      android:layout_width = "match_parent" 
      android:layout_weight = "20" 
      android:layout_height = "0dp" 
      android:textColor = "#368DEB" 
      android:id = "@+id/txtCreatAccount" 
      android:gravity = "center" 
      android:textStyle = "bold" 
      android:textSize = "25sp" /> 
   <Button 
      android:text = "Sign In" 
      android:layout_width = "match_parent" 
      android:layout_weight = "15" 
      android:layout_height = "0dp" 
      android:background = "@drawable/btnSignInStyle" 
      android:id = "@+id/btnSignIn" 
      android:layout_marginLeft = "20dp" 
      android:layout_marginRight = "20dp" 
      android:textSize = "15sp" /> 
   <Button 
      android:text = "Sign Up" 
      android:layout_width = "match_parent" 
      android:layout_weight = "15" 
      android:layout_height = "0dp" 
      android:background = "@drawable/btnSignUpStyle" 
      android:id = "@+id/btnSignUp" 
      android:layout_marginLeft = "20dp" 
      android:layout_marginRight = "20dp" 
      android:textSize = "15sp" /> 
   <RelativeLayout 
      android:layout_width = "match_parent" 
      android:layout_height = "0dp" 
      android:layout_weight = "50" 
      android:minWidth = "25px" 
      android:minHeight = "25px"> 
      <ProgressBar 
         android:layout_width = "wrap_content" 
         android:layout_height = "wrap_content" 
         android:id = "@+id/progressBar1" 
         android:background = "@drawable/progressBarStyle" 
         android:layout_centerInParent="true" 
         android:indeterminate = "true" 
         xmlns:tools = "
            http://schemas.android.com/tools" 
         tools:visibility = "invisible" /> 
   </RelativeLayout> 
</LinearLayout>

建立使用者介面後,務必設定按鈕的樣式以使其看起來更具吸引力。為此,在drawable資料夾下建立一個新的XML檔案,並將檔案命名為btnSignInStyle.xml

在XML檔案中,新增以下程式碼行:

<selector xmlns:android = "http://schemas.android.com/apk/res/android"> 
   <item android:state_pressed = "false"> 
      <layer-list> 
         <item android:right = "5dp" android:top = "5dp"> 
            <shape> 
               <corners android:radius = "2dp"/> 
               <solid android:color = "#D6D6D6"/> 
            </shape> 
         </item>  
         <item android:left = "2dp" android:bottom = "2dp"> 
            <shape> 
               <corners android:radius = "4dp"/> 
               <gradient android:angle = "270" 
                  android:endColor = "#486EA9" android:startColor = "#486EA9"/> 
               <stroke android:width = "1dp" android:color = "#BABABA"/> 
               <padding android:bottom = "10dp" 
                  android:right = "10dp" android:left = "10dp" android:top = "10dp"/> 
            </shape>  
         </item> 
      </layer-list> 
   </item> 
   <item android:state_pressed = "true"> 
      <layer-list> 
         <item android:right = "5dp" android:top = "5dp"> 
            <shape> 
               <corners android:radius = "2dp"/> 
               <solid android:color = "#D6D6D6"/> 
            </shape> 
         </item>  
         <item android:left = "2dp" android:bottom = "2dp"> 
            <shape> 
               <corners android:radius = "4dp"/> 
               <gradient android:angle = "270" 
                  android:endColor = "#79C791" android:startColor = "#486EA9"/> 
               <stroke android:radius = "4dp" android:color = "#BABABA"/>
               <padding android:bottom = "10dp" 
                  android:right = "10dp" android:left = "10dp" android:top = "10dp"/> 
            </shape> 
         </item> 
      </layer-list> 
  </item> 
</selector>          

上面的程式碼設定載入時按鈕的顏色,以及單擊時的顏色,還設定按鈕的圓角。

接下來,我們為signup按鈕建立與上面類似的樣式XML。為此,在drawable資料夾下建立另一個XML,並將其命名為btnSignUpStyle.xml。它將繼承btnSignInStyle.xml中的所有內容。唯一的區別是按鈕的漸變開始和結束顏色。

btnSignUpStyle.xml中的startColorendColor更改為

<gradient android:angle="270" 
   android:endColor="#008000" android:startColor="#008000"/>

轉到layout資料夾並建立一個新的AXML檔案,並將其命名為registerDailog.axml。此檔案將包含應用程式中新使用者的註冊詳細資訊。此頁面將包含三個EditTexts和一個提交資料的按鈕。在您的線性佈局程式碼中新增以下程式碼。

<EditText 
   android:layout_width = "match_parent" 
   android:layout_marginBottom = "10dp" 
   android:layout_marginTop = "25dp" 
   android:layout_marginRight = "25dp" 
   android:layout_marginLeft = "25dp" 
   android:layout_height = "35dp" 
   android:paddingLeft = "10dp" 
   android:id = "@+id/txtUsername" 
   android:hint = "Username" 
   android:textColor = "#000" /> 
<EditText 
   android:layout_width = "match_parent" 
   android:layout_height = "35dp" 
   android:id = "@+id/txtEmail" 
   android:layout_marginBottom = "10dp" 
   android:layout_marginTop = "25dp" 
   android:layout_marginRight = "25dp" 
   android:layout_marginLeft = "25dp" 
   android:paddingLeft = "10dp"
   android:textColor = "#000" 
   android:hint = "Email" /> 
<EditText 
   android:layout_width = "match_parent" 
   android:layout_height = "35dp" 
   android:layout_marginBottom = "10dp" 
   android:layout_marginTop = "25dp" 
   android:layout_marginRight = "25dp" 
   android:layout_marginLeft = "25dp" 
   android:paddingLeft = "10dp" 
   android:textColor = "#000" 
   android:id = "@+id/txtPassword" 
   android:hint = "Password" />
<Button 
   android:text = "Sign Up" 
   android:layout_width = "match_parent" 
   android:layout_height = "wrap_content" 
   android:id = "@+id/btnSave" 
   android:textSize = "20dp" 
   android:textColor = "#fff" 
   android:textStyle = "bold" 
   android:height = "70dp" 
   android:background = "@drawable/btnSignUpStyle" 
   android:paddingLeft = "5dp" 
   android:paddingRight = "5dp" 
   android:paddingTop = "5dp" 
   android:paddingBottom = "5dp" 
   android:layout_marginLeft = "25dp" 
   android:layout_marginRight = "25dp" 
   android:layout_centerHorizontal = "true" />

接下來,新增一個名為signUpDialog.cs的新類。此類將包含建立對話方塊所需的程式碼。以下示例顯示了程式碼。

public class OnSignUpEvent:EventArgs { 
   private string myUserName; 
   private string myEmail; 
   private string myPassword; 
   public string UserName { 
      get { 
         return myUserName; 
      } 
      set{ 
         myUserName = value;
      } 
   } 
      
   public string Email { 
      get { 
         return myEmail; 
      } 
      set { 
         myEmail = value; 
      } 
   } 
      
   public string Password { 
      get { 
         return myPassword; 
      } 
      set { 
         myPassword = value; 
      } 
   }  
   public OnSignUpEvent(string username, string 
      email, string password):base() { 
      UserName = username; 
      Email = email; 
      Password = password; 
   } 
     
   class SignUpDialog:DialogFragment { 
      private EditText txtUsername; 
      private EditText txtEmail; 
      private EditText txtPassword; 
      private Button btnSaveSignUp; 
      public event EventHandler<OnSignUpEvent> onSignUpComplete; 
      public override View OnCreateView(LayoutInflater inflater, 
         ViewGroup container, Bundle savedInstanceState) { 
         base.OnCreateView(inflater, container, savedInstanceState);       
         var view = inflater.Inflate(Resource.Layout.registerDialog, container, false); 
         txtUsername = view.FindViewById<EditText>(Resource.Id.txtUsername); 
         txtEmail = view.FindViewById<EditText>(Resource.Id.txtEmail); 
         txtPassword = view.FindViewById<EditText>(Resource.Id.txtPassword);
         btnSaveSignUp = view.FindViewById<Button>(Resource.Id.btnSave); 
         btnSaveSignUp.Click += btnSaveSignUp_Click;   
         return view; 
      }  
      void btnSaveSignUp_Click(object sender, EventArgs e) { 
         onSignUpComplete.Invoke(this, new OnSignUpEvent(txtUsername.Text, 
         
            txtEmail.Text, txtPassword.Text)); 
         this.Dismiss(); 
      } 
   }
}   

在上面的程式碼中,我們使用了getset屬性。get方法返回一個變數,而set方法為返回的變數賦值。這是一個示例:

public string Color { 
   get { 
      return color;  
   } 
   set { 
      color = value;  
   } 
}

在我們之前的示例中,我們建立了一個覆蓋檢視的方法。在方法內部,我們建立了一個名為viewvar,它引用了layout資料夾中包含的registerDialog.axml

接下來,轉到mainActivity.cs建立對話方塊片段。

private Button signUp; 
private Button submitNewUser; 
private EditText txtUsername; 
private EditText txtEmail; 
private EditText txtPassword; 

protected override void OnCreate(Bundle bundle) { 
   base.OnCreate(bundle);  
   SetContentView(Resource.Layout.Main);
   signUp = FindViewById<Button>(Resource.Id.btnSignUp); 
   submitNewUser = FindViewById<Button>(Resource.Id.btnSave); 
   txtUsername = FindViewById<EditText>(Resource.Id.txtUsername); 
   txtEmail = FindViewById<EditText>(Resource.Id.txtEmail); 
   txtPassword = FindViewById<EditText>(Resource.Id.txtPassword); 
            
   signUp.Click += (object sender, EventArgs args) => { 
      FragmentTransaction transFrag = FragmentManager.BeginTransaction(); 
      SignUpDialog diagSignUp = new SignUpDialog(); 
      diagSignUp.Show(transFrag, "Fragment Dialog"); 
      diagSignUp.onSignUpComplete += diagSignUp_onSignUpComplete; 
   }; 
}  
void diagSignUp_onSignUpComplete(object sender, OnSignUpEvent e) { 
   StartActivity(typeof(Activity2)); 
}             

上面的程式碼包含一個按鈕單擊事件,單擊該事件將載入signUp對話方塊。在按鈕單擊事件中,我們建立了一個SignUpDialog類,該類載入registerDialog.axml檔案。

然後,我們使用FragmentTransaction transFrag = FragmentManager.BeginTransaction();將我們的registerDialog頁面顯示為Android對話方塊片段。

我們將新增另一個名為home.axml.axml檔案。此佈局將是使用者成功登入系統後的登入螢幕。在此佈局中,我們將新增一個textview,如下面的程式碼所示。

<TextView 
   android:text = "You have been succesfully registered. Welcome!" 
   android:textAppearance = "?android:attr/textAppearanceLarge" 
   android:layout_width = "match_parent" 
   android:layout_height = "wrap_content" 
   android:id = "@+id/textView1" /> 

接下來,我們建立一個名為Activity2.cs的最終活動。在此活動中,我們將使用findViewById查詢home.axml

最後,構建並執行您的應用程式。它將顯示以下螢幕作為輸出。

Build App

Xamarin - 部署您的應用程式

完成應用程式構建過程後,務必在物理Android裝置上使用此應用程式,或允許其他人下載您的應用程式並將其安裝到他們的裝置上。

釋出您的應用程式

在釋出您的應用程式之前,務必將其轉換為Android系統可以讀取的格式。這種格式稱為apk檔案。要建立apk檔案

  • 開啟您的專案。

  • 轉到構建選單並選擇配置管理器

  • 在配置管理器上,將活動解決方案配置設定為釋出應用程式。

Configuration Manager

接下來,再次單擊構建選單並選擇匯出Android包(.apk)

Export Andriod Package

完成後,apk檔案將儲存在您的專案資料夾/bin/Release中。

釋出您的應用程式

有三種釋出應用程式的方法:

線上附件

這涉及將您的apk檔案作為附件上傳到網上。然後,擁有Android裝置的使用者可以下載並直接將您的應用程式安裝到他們的裝置上。

Google Play商店

Play商店是Android應用程式最大的市場。要將您的應用程式上傳到Play商店,您需要擁有Google的開發者帳戶。開發者帳戶建立一次,獲得許可證的費用為25美元。

手動安裝

手動安裝涉及將生成的.apk檔案直接安裝到物理裝置上。將檔案複製到Android裝置的物理記憶體或SD卡中,然後從裝置執行該檔案。

預設情況下,Android會阻止安裝非Play商店的應用程式。要安裝您的應用程式,您必須啟用它以接受來自設定的應用程式安裝。為此,請轉到裝置上的設定,查詢安全選單,然後選中“允許安裝來自未知來源的應用程式”。

Security
廣告
© . All rights reserved.