完成環境配置后開始第一個簡單項目。打開 Visual Studio 新建一個 Xamarin.Android 項目 “HelloAndroid”。(GitHub:https://github.com/ZhangGaoxing/xamarin-android-demo/tree/master/HelloAndroid)
解決方案結構如下
1. 項目結構分析
Properties 存放著應用的一些配置信息。直接雙擊 “Properties” 可以設置應用的一些屬性。AndroidManifest.xml 則是 Android 應用的配置文件,像活動,權限等都要在其中注冊,但不需要手動注冊,編譯時 Xamarin 會自動完成。AssemblyInfo.cs 存放應用的編譯信息,像名稱,描述,版本等。
引用 與一般的 .Net 項目一樣。
Components 暫時不了解怎么用……
Assets 下存放的是原生的資源文件,像文本之類的,不會經過編譯,直接打包。目錄下有一個簡單的幫助文件。
Resources 下存放的都是要經過編譯的資源文件。和 Android 項目下的 res 目錄是一樣的,drawable 下存放的是圖片文件,layout 下是應用布局文件,value 下則是字符串。和 Assets 目錄一樣,也有一個簡單的幫助文件。Resource.Designer.cs 則是一些自動生成的代碼。
MainActivity.cs 則是默認創建的主活動。
2. 代碼說明
由于空項目自動創建了一個活動和一個布局,則使用默認的模板。
Main.axml
雙擊 Main.axml 打開布局編輯器,你可以和正常的 .Net 項目一樣從工具箱中拖拽控件,也可以使用類似Xaml的方式來編寫布局。這里我們需要一個 Button 用來點擊,和一個 TextView 用來顯示 “Hello, Android”。每創建一個控件,相應的 id 會自動添加到 Resource.Id 中(找不到 id 的話請重新生成一下項目)。效果示意圖如下
界面 xml 代碼如下
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/showHello" /> <Button android:text="Click Me" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/sayHello" /> </LinearLayout>
MainActivity.cs
Android 項目中任何活動都要重寫 onCreate() 方法,同樣的 Xamarin 也已經自動創建了一個符合 C# 命名規則的 OnCreate() 方法。和 Android 項目一樣,活動創建完成后需要加載布局,SetContentView () 方法沒變只不過符合了 C# 的命名規則,將 Resource.Layout 下的布局傳入即可。這里傳入的是 Resource.Layout.Main 。
public class MainActivity : Activity {protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // 加載布局 SetContentView (Resource.Layout.Main); } }
創建事件首先要獲取布局中的控件,在 Xamarin 中可以使用泛型方法 FindViewById<T>() 來獲取控件,需要傳入一個 id 值。
// 獲取布局中的控件 Button say = FindViewById<Button>(Resource.Id.sayHello); TextView show = FindViewById<TextView>(Resource.Id.showHello);
接下來創建 Button 的 Click 方法。和一般的 .Net 項目一樣,直接上代碼。
// 綁定 Click 事件 say.Click += (sender, e) => { };
這個簡單的項目實現的是點擊計數,并使用 Toast 通知顯示,下面給出完整代碼
using Android.App; using Android.Widget; using Android.OS; namespace HelloAndroid { [Activity(Label = "HelloAndroid", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { int count = 0; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // 加載布局 SetContentView (Resource.Layout.Main); // 獲取布局中的控件 Button say = FindViewById<Button>(Resource.Id.sayHello); TextView show = FindViewById<TextView>(Resource.Id.showHello); // 綁定 Click 事件 say.Click += (sender, e) => { count++; show.Text = "Hello, Android"; say.Text = $"You Clicked {count}"; // Toast 通知 Toast.MakeText(this, $"You Clicked {count}", ToastLength.Short).Show(); }; } } }
效果圖(需要注意的是,使用模擬器調試時應用會直接閃退,應該是應用支持文件沒傳進模擬器吧,我猜的。真機調試時第一次安裝了三個應用,一個運行時應用,一個API支持應用,還有一個自己的應用。)
文章列表