Mono for Android 示例项目教程
1. 项目的目录结构及介绍
Mono for Android 示例项目的目录结构如下:
monodroid-samples/
├── HelloWorld/
│ ├── HelloWorld/
│ │ ├── MainActivity.cs
│ │ ├── Main.axml
│ │ ├── Properties/
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── AssemblyInfo.cs
│ │ ├── Resources/
│ │ │ ├── drawable/
│ │ │ ├── layout/
│ │ │ ├── values/
│ │ │ ├── Resource.designer.cs
│ ├── HelloWorld.sln
├── MyFirstApp/
│ ├── MyFirstApp/
│ │ ├── MainActivity.cs
│ │ ├── Main.axml
│ │ ├── Properties/
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── AssemblyInfo.cs
│ │ ├── Resources/
│ │ │ ├── drawable/
│ │ │ ├── layout/
│ │ │ ├── values/
│ │ │ ├── Resource.designer.cs
│ ├── MyFirstApp.sln
├── ...
目录结构介绍
HelloWorld/
和MyFirstApp/
是示例项目的根目录。- 每个示例项目包含一个解决方案文件(如
HelloWorld.sln
)和一个项目文件夹(如HelloWorld/
)。 - 项目文件夹中包含主要的代码文件(如
MainActivity.cs
)和布局文件(如Main.axml
)。 Properties/
目录包含项目的配置文件(如AndroidManifest.xml
)和程序集信息文件(如AssemblyInfo.cs
)。Resources/
目录包含项目的资源文件,如图片(drawable/
)、布局(layout/
)和字符串(values/
)。
2. 项目的启动文件介绍
每个示例项目的启动文件是 MainActivity.cs
,它继承自 Android.App.Activity
类,并重写了 OnCreate
方法。以下是一个典型的 MainActivity.cs
文件的内容:
using Android.App;
using Android.OS;
using Android.Widget;
namespace HelloWorld
{
[Activity(Label = "HelloWorld", 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, Xamarin!";
};
}
}
}
启动文件介绍
[Activity(Label = "HelloWorld", MainLauncher = true, Icon = "@drawable/icon")]
属性定义了活动的标签、图标和是否作为主启动器。OnCreate
方法在活动创建时调用,用于设置布局文件和初始化控件。
3. 项目的配置文件介绍
每个示例项目的配置文件主要位于 Properties/
目录下,最重要的配置文件是 AndroidManifest.xml
。以下是一个典型的 AndroidManifest.xml
文件的内容:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="HelloWorld"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="15" />
<application android:label="HelloWorld" android:icon="@drawable/icon">
<activity android:name=".MainActivity"
android:label="HelloWorld">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>