在Visual Studio 2015中,可以使用 Xamarin 开发工具创建跨平台的移动应用程序,包括 安卓 和 iOS。在本教程中,我们将会演示如何在 Visual Studio 2015 内使用 Xamarin 开发 安卓 应用程序,并为该应用创建一个登入界面。
# 准备工作
1. 安装 Visual Studio 2015(Community、Professional 或 Enterprise版本均可)。
2. 安装 Xamarin。通常在 Visual Studio 安装过程中可以选择 Xamarin 作为一个组件。如果没有安装 Xamarin,可以在 https://www.xamarin.com 实现下载并安装。
# 创建 安卓 项目
1. 打开 Visual Studio 2015,选择 新建项目...。
2. 在模板中选择 Installed > Templates > Visual C# > 安卓 > Blank App(安卓)。
3. 为项目命名,例如 LoginApp,然后点击 确定。
Visual Studio 将会创建一个新的基于 Xamarin 的 安卓 应用项目。
# 设计登入界面
1. 在解决方案资源管理器中展开 Resources > layout 目录,打开 Main.axml 文件以编辑 安卓 应用的 UI。
2. 使用设计器或代码创建登入界面。这里先以代码为例,将以下 XML 代码替换 Main.axml 文件的内容
```xml
安卓:id=@+id/loginRelativeLayout
安卓:layout,width=match,parent
安卓:layout,height=match,parent
安卓:padding=20dp >
安卓:id=@+id/loginTitle
安卓:layout,width=match,parent
安卓:layout,height=wrap,content
安卓:text=登入
安卓:textSize=24sp
安卓:gravity=center />
安卓:id=@+id/usernameInput
安卓:layout,width=match,parent
安卓:layout,height=wrap,content
安卓:hint=用户名
安卓:inputType=text
安卓:layout,below=@+id/loginTitle
安卓:layout,marginTop=20dp />
安卓:id=@+id/passwordInput
安卓:layout,width=match,parent
安卓:layout,height=wrap,content
安卓:hint=密码
安卓:inputType=textPassword
安卓:layout,below=@+id/usernameInput
安卓:layout,marginTop=10dp />
安卓:id=@+id/loginButton
安卓:layout,width=match,parent
安卓:layout,height=wrap,content
安卓:text=登入
安卓:layout,below=@+id/passwordInput
安卓:layout,marginTop=20dp />
```
3. 保存 Main.axml 文件。
# 编写登入逻辑
1. 在解决方案资源管理器中展开 LoginApp 项目,打开 MainActivity.cs。
2. 在 MainActivity 类中找到 OnCreate(Bundle) 方法,在该方法内添加以下代码,以关联布局中的控件
```csharp
Button loginButton = FindViewById