Xamarin.Forms 快速入门Xamarin.Forms Quickstart

本演练介绍如何创建一个应用程序,它将字母数字电话号码(由用户输入)转换为数字电话号码,然后呼叫该号码。This walkthrough demonstrates how to create an application that translates an alphanumeric phone number entered by the user into a numeric phone number, and that calls the number. 最终的应用程序如下所示:The final application is shown below:

Visual Studio 入门Get started with Visual Studio

  1. 在“开始”屏幕中,启动 Visual Studio。In the Start screen, launch Visual Studio. 这会打开起始页:This opens the start page:

  2. 在 Visual Studio 中,单击“创建新项目...”以创建新项目:In Visual Studio, click Create new project... to create a new project:

  3. 在“新建项目”对话框中,单击“跨平台”,选择“移动应用(Xamarin.Forms)”模板,将“名称”设为“Phoneword”,为项目选择合适的位置,然后单击“确定”按钮:In the New Project dialog, click Cross-Platform, select the Mobile App (Xamarin.Forms) template, set the Name to Phoneword, choose a suitable location for the project and click the OK button:

    备注

    本快速入门中的 C# 和 XAML 片段要求将解决方案命名为“Phoneword”。The C# and XAML snippets in this quickstart require the solution be named Phoneword. 将这些指令中的代码复制到项目中时,使用不同的解决方案名称将导致大量生成错误。Using a different solution name will result in numerous build errors when you copy code from these instructions into the projects.

  4. 在“新的跨平台应用”对话框中,单击“空白应用”,选择“.NET Standard”作为代码共享策略,然后单击“确定”按钮:In the New Cross Platform App dialog, click Blank App, select .NET Standard as the Code Sharing Strategy, and click the OK button:

  5. 在“解决方案资源管理器”的“Phoneword”项目中,双击 MainPage.xaml 将其打开:In Solution Explorer, in the Phoneword project, double-click MainPage.xaml to open it:

  6. 在“MainPage.xaml”中,删除所有模板代码并将其替换为以下代码。In MainPage.xaml, remove all of the template code and replace it with the following code. 此代码以声明方式定义页面上的用户界面:This code declaratively defines the user interface for the page:

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="Phoneword.MainPage">
        <ContentPage.Padding>
            <OnPlatform x:TypeArguments="Thickness">
                <On Platform="iOS" Value="20, 40, 20, 20" />
                <On Platform="Android, UWP" Value="20" />
            </OnPlatform>
        </ContentPage.Padding>
        <StackLayout>
          <Label Text="Enter a Phoneword:" />
          <Entry x:Name="phoneNumberText" Text="1-855-XAMARIN" />
          <Button Text="Translate" Clicked="OnTranslate" />
          <Button x:Name="callButton" Text="Call" IsEnabled="false" Clicked="OnCall" />
        </StackLayout>
    </ContentPage>
    

    Ctrl+S,保存对 MainPage.xaml 所做的更改,然后关闭文件。Save the changes to MainPage.xaml by pressing CTRL+S, and close the file.

  7. 在“解决方案资源管理器”中,展开“MainPage.xaml”,然后双击 MainPage.xaml.cs 将其打开:In Solution Explorer, expand MainPage.xaml and double-click MainPage.xaml.cs to open it:

  8. 在“MainPage.xaml.cs”中,删除所有模板代码并将其替换为以下代码。In MainPage.xaml.cs, remove all of the template code and replace it with the following code. 如果分别在用户界面中单击“翻译”和“调用”按钮,作为响应,将分别执行 OnTranslateOnCall 方法:The OnTranslate and OnCall methods will be executed in response to the Translate and Call buttons being clicked in the user interface, respectively:

    using System;
    using Xamarin.Forms;
    
    namespace Phoneword
    {
        public partial class MainPage : ContentPage
        {
            string translatedNumber;
    
            public MainPage ()
            {
                InitializeComponent ();
            }
    
            void OnTranslate (object sender, EventArgs e)
            {
                translatedNumber = PhonewordTranslator.ToNumber (phoneNumberText.Text);
                if (!string.IsNullOrWhiteSpace (translatedNumber)) {
                    callButton.IsEnabled = true;
                    callButton.Text = "Call " + translatedNumber;
                } else {
                    callButton.IsEnabled = false;
                    callButton.Text = "Call";
                }
            }
    
            async void OnCall (object sender, EventArgs e)
            {
                if (await this.DisplayAlert (
                        "Dial a Number",
                        "Would you like to call " + translatedNumber + "?",
                        "Yes",
                        "No")) {
                    var dialer = DependencyService.Get<IDialer> ();
                    if (dialer != null)
                        dialer.Dial (translatedNumber);
                }
            }
        }
    }
    

    备注

    尝试在此时构建应用程序将导致稍后要修复的错误。Attempting to build the application at this point will result in errors that will be fixed later.

    Ctrl+S,保存对 MainPage.xaml.cs 所做的更改,然后关闭文件。Save the changes to MainPage.xaml.cs by pressing CTRL+S, and close the file.

  9. 在“解决方案资源管理器”中,右键单击“Phoneword”项目,然后选择“添加”>“新建项...”:In Solution Explorer, right click on the Phoneword project and select Add > New Item...:

  10. 在“添加新项”对话框中,选择“Visual C#”>“代码”>“类”,将新文件命名为 PhoneTranslator,然后单击“添加”按钮:In the Add New Item dialog, select Visual C# > Code > Class, name the new file PhoneTranslator, and click the Add button:

  11. 在“PhoneTranslator.cs”中,删除所有模板代码并将其替换为以下代码。In PhoneTranslator.cs, remove all of the template code and replace it with the following code. 此代码会将手机词翻译为电话号码:This code will translate a phone word to a phone number:

    using System.Text;
    
    namespace Phoneword
    {
        public static class PhonewordTranslator
        {
            public static string ToNumber(string raw)
            {
                if (string.IsNullOrWhiteSpace(raw))
                    return null;
    
                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);
                        // Bad character?
                        else
                            return null;
                    }
                }
                return newNumber.ToString();
            }
    
            static bool Contains(this string keyString, char c)
            {
                return keyString.IndexOf(c) >= 0;
            }
    
            static readonly string[] digits = {
                "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
            };
    
            static int? TranslateToNumber(char c)
            {
                for (int i = 0; i < digits.Length; i++)
                {
                    if (digits[i].Contains(c))
                        return 2 + i;
                }
                return null;
            }
        }
    }
    

    通过按 Ctrl+S,保存对 PhoneTranslator.cs 所做的更改,然后关闭文件。Save the changes to PhoneTranslator.cs by pressing CTRL+S, and close the file.

  12. 在“解决方案资源管理器”中,右键单击“Phoneword”项目,然后选择“添加”>“新建项...”:In Solution Explorer, right click on the Phoneword project and select Add > New Item...:

  13. 在“添加新项”对话框中,选择“Visual C#”>“代码”>“界面”,将新文件命名为 IDialer,然后单击“添加”按钮:In the Add New Item dialog, select Visual C# > Code > Interface, name the new file IDialer, and click the Add button:

  14. 在“IDialer.cs”中,删除所有模板代码并将其替换为以下代码。In IDialer.cs, remove all of the template code and replace it with the following code. 此代码将定义 Dial 方法,必须在每个平台上实现此方法,才可拨打翻译后的电话号码:This code defines a Dial method that must be implemented on each platform to dial a translated phone number:

    namespace Phoneword
    {
        public interface IDialer
        {
            bool Dial(string number);
        }
    }
    

    通过按 Ctrl+S,保存对 IDialer.cs 所做的更改,然后关闭文件。Save the changes to IDialer.cs by pressing CTRL+S, and close the file.

    备注

    此时完成了应用程序的常用代码。The common code for the application is now complete. 此时,可将特定于平台的电话拨号程序实现为 DependencyServicePlatform-specific phone dialer code will now be implemented as a DependencyService.

  15. 在“解决方案资源管理器”中,右键单击“Phoneword.iOS”项目,然后选择“添加”>“新建项...”:In Solution Explorer, right click on the Phoneword.iOS project and select Add > New Item...:

  16. 在“添加新项”对话框中,选择“Apple”>“代码”>“类”,将新文件命名为 PhoneDialer,然后单击“添加”按钮:In the Add New Item dialog, select Apple > Code > Class, name the new file PhoneDialer, and click the Add button:

  17. 在“PhoneDialer.cs”中,删除所有模板代码并将其替换为以下代码。In PhoneDialer.cs, remove all of the template code and replace it with the following code. 此代码将创建 Dial 方法,此方法将在 iOS 平台上用于拨打翻译后的电话号码:This code creates the Dial method that will be used on the iOS platform to dial a translated phone number:

    using Foundation;
    using Phoneword.iOS;
    using UIKit;
    using Xamarin.Forms;
    
    [assembly: Dependency(typeof(PhoneDialer))]
    namespace Phoneword.iOS
    {
        public class PhoneDialer : IDialer
        {
            public bool Dial(string number)
            {
                return UIApplication.SharedApplication.OpenUrl (
                    new NSUrl ("tel:" + number));
            }
        }
    }
    

    通过按 Ctrl+S,保存对 PhoneDialer.cs 所做的更改,然后关闭文件。Save the changes to PhoneDialer.cs by pressing CTRL+S, and close the file.

  18. 在“解决方案资源管理器”中,右键单击“Phoneword.Android”项目,然后选择“添加”>“新建项...”:In Solution Explorer, right click on the Phoneword.Android project and select Add > New Item...:

  19. 在“添加新项”对话框中,选择“Visual C#”>“Android”>“类”,将新文件命名为 PhoneDialer,然后单击“添加”按钮:In the Add New Item dialog, select Visual C# > Android > Class, name the new file PhoneDialer, and click the Add button:

  20. 在“PhoneDialer.cs”中,删除所有模板代码并将其替换为以下代码。In PhoneDialer.cs, remove all of the template code and replace it with the following code. 此代码将创建 Dial 方法,此方法将在 Android 平台上用于拨打翻译后的电话号码:This code creates the Dial method that will be used on the Android platform to dial a translated phone number:

    using Android.Content;
    using Android.Telephony;
    using Phoneword.Droid;
    using System.Linq;
    using Xamarin.Forms;
    using Uri = Android.Net.Uri;
    
    [assembly: Dependency(typeof(PhoneDialer))]
    namespace Phoneword.Droid
    {
        public class PhoneDialer : IDialer
        {
            public bool Dial(string number)
            {
                var context = MainActivity.Instance;
                if (context == null)
                    return false;
    
                var intent = new Intent (Intent.ActionDial);
                intent.SetData (Uri.Parse ("tel:" + number));
    
                if (IsIntentAvailable (context, intent)) {
                    context.StartActivity (intent);
                    return true;
                }
    
                return false;
            }
    
            public static bool IsIntentAvailable(Context context, Intent intent)
            {
                var packageManager = context.PackageManager;
    
                var list = packageManager.QueryIntentServices (intent, 0)
                    .Union (packageManager.QueryIntentActivities (intent, 0));
    
                if (list.Any ())
                    return true;
    
                var manager = TelephonyManager.FromContext (context);
                return manager.PhoneType != PhoneType.None;
            }
        }
    }
    

    请注意,若要更好地理解此代码,需要使用最新 Android API。Note that this code assumes that you are using the latest Android API. 通过按 Ctrl+S,保存对 PhoneDialer.cs 所做的更改,然后关闭文件。Save the changes to PhoneDialer.cs by pressing CTRL+S, and close the file.

  21. 在“解决方案资源管理器”的“Phoneword.Android”项目中,双击“MainActivity.cs”将其打开,然后删除所有模板代码并将其替换成下列代码:In Solution Explorer, in the Phoneword.Android project, double-click MainActivity.cs to open it, remove all of the template code and replace it with the following code:

    using Android.App;
    using Android.Content.PM;
    using Android.OS;
    
    namespace Phoneword.Droid
    {
        [Activity(Label = "Phoneword", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true,
                  ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
        public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
            internal static MainActivity Instance { get; private set; }
    
            protected override void OnCreate(Bundle bundle)
            {
                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
    
                base.OnCreate(bundle);
                Instance = this;
                global::Xamarin.Forms.Forms.Init(this, bundle);
                LoadApplication(new App());
            }
        }
    }
    

    按 Ctrl+S,保存对 MainActivity.cs 所做的更改,然后关闭文件。Save the changes to MainActivity.cs by pressing CTRL+S, and close the file.

  22. 在“解决方案资源管理器”的“Phoneword.Android”项目中,双击“属性”,然后选择“Android 清单”选项卡:In Solution Explorer, in the Phoneword.Android project, double-click Properties and select the Android Manifest tab:

  23. 在“所需的权限”部分中,启用“CALL_PHONE”权限。In the Required permissions section, enable the CALL_PHONE permission. 这将向应用程序授予进行电话呼叫的权限:This gives the application permission to place a phone call:

    通过按 Ctrl+S,保存对清单所做的更改,然后关闭文件。Save the changes to the manifest by pressing CTRL+S, and close the file.

  24. 右键单击 Android 应用程序项目并选择“设为启动项目”。Right-click on the Android application project and choose Set as startup project.

  25. 使用“绿色箭头”工具栏按钮运行 Android 应用或在菜单中选择“调试”>“开始调试”。Run the Android app using the "green arrow" toolbar button, or select Debug > Start Debugging from the menu.

    警告

    所有模拟器都不支持电话呼叫,因此该功能可能无效。Phone calls are not supported on all the simulators, so that feature may not work.

  26. 如果拥有 iOS 设备并符合 Xamarin.Forms 开发的 Mac 系统要求,请使用类似技术将应用部署到 iOS 设备。If you have an iOS device and meet the Mac system requirements for Xamarin.Forms development, use a similar technique to deploy the app to the iOS device. 或者,将应用部署到 iOS 远程模拟器Alternatively, deploy the app to the iOS remote simulator.

Visual Studio for Mac 入门Get started with Visual Studio for Mac

  1. 启动 Visual Studio for Mac,然后在起始页上单击“新建项目...”创建新项目:Launch Visual Studio for Mac, and on the start page click New Project... to create a new project:

  2. 在“为新项目选择一个模板”对话框中,单击“多平台”>“应用”,选择“空白窗体应用”模板,然后单击“下一步”按钮:In the Choose a template for your new project dialog, click Multiplatform > App, select the Blank Forms App template, and click the Next button:

  3. 在“配置空白表单应用”对话框中,将新应用命名为“Phoneword”,确保选中“使用 .NET Standard”单选按钮,然后单击“下一步”按钮:In the Configure your Blank Forms app dialog, name the new app Phoneword, ensure that the Use .NET Standard radio button is selected, and click the Next button:

  4. 在“配置新空白表单应用”对话框中,将“解决方案”和“项目”名称保留设置为“Phoneword”,为项目选择合适的位置,然后单击“创建”按钮创建项目:In the Configure your new Blank Forms app dialog, leave the Solution and Project names set to Phoneword, choose a suitable location for the project, and click the Create button to create the project:

    备注

    本快速入门中的 C# 和 XAML 片段要求将解决方案命名为“Phoneword”。The C# and XAML snippets in this quickstart require the solution be named Phoneword. 将这些指令中的代码复制到项目中时,使用不同的解决方案名称将导致大量生成错误。Using a different solution name will result in numerous build errors when you copy code from these instructions into the projects.

  5. 在“Solution Pad”中,双击 MainPage.xaml将其打开:In the Solution Pad, double-click MainPage.xaml to open it:

  6. 在“MainPage.xaml”中,删除所有模板代码并将其替换为以下代码。In MainPage.xaml, remove all of the template code and replace it with the following code. 此代码以声明方式定义页面上的用户界面:This code declaratively defines the user interface for the page:

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="Phoneword.MainPage">
        <ContentPage.Padding>
            <OnPlatform x:TypeArguments="Thickness">
                <On Platform="iOS" Value="20, 40, 20, 20" />
                <On Platform="Android, UWP" Value="20" />
            </OnPlatform>
        </ContentPage.Padding>
        <StackLayout>
          <Label Text="Enter a Phoneword:" />
          <Entry x:Name="phoneNumberText" Text="1-855-XAMARIN" />
          <Button Text="Translate" Clicked="OnTranslate" />
          <Button x:Name="callButton" Text="Call" IsEnabled="false" Clicked="OnCall" />
        </StackLayout>
    </ContentPage>
    

    通过选择“文件”>“保存”,或按 ⌘ + S,保存对 MainPage.xaml 所做的更改,然后关闭文件。Save the changes to MainPage.xaml by choosing File > Save (or by pressing ⌘ + S), and close the file.

  7. 在“Solution Pad”中,双击 MainPage.xaml.cs 将其打开:In the Solution Pad, double-click MainPage.xaml.cs to open it:

  8. 在“MainPage.xaml.cs”中,删除所有模板代码并将其替换为以下代码。In MainPage.xaml.cs, remove all of the template code and replace it with the following code. 如果分别在用户界面上单击“翻译”和“调用”按钮,作为响应,将分别执行 OnTranslateOnCall 方法:The OnTranslate and OnCall methods will be executed in response to the Translate and Call buttons being clicked on the user interface, respectively:

    using System;
    using Xamarin.Forms;
    
    namespace Phoneword
    {
        public partial class MainPage : ContentPage
        {
            string translatedNumber;
    
            public MainPage ()
            {
                InitializeComponent ();
            }
    
            void OnTranslate (object sender, EventArgs e)
            {
                translatedNumber = PhonewordTranslator.ToNumber (phoneNumberText.Text);
                if (!string.IsNullOrWhiteSpace (translatedNumber)) {
                    callButton.IsEnabled = true;
                    callButton.Text = "Call " + translatedNumber;
                } else {
                    callButton.IsEnabled = false;
                    callButton.Text = "Call";
                }
            }
    
            async void OnCall (object sender, EventArgs e)
            {
                if (await this.DisplayAlert (
                        "Dial a Number",
                        "Would you like to call " + translatedNumber + "?",
                        "Yes",
                        "No")) {
                    var dialer = DependencyService.Get<IDialer> ();
                    if (dialer != null)
                        dialer.Dial (translatedNumber);
                }
            }
        }
    }
    

    备注

    尝试在此时构建应用程序将导致稍后要修复的错误。Attempting to build the application at this point will result in errors that will be fixed later.

    通过选择“文件”>“保存”,或按 ⌘ + S,保存对 MainPage.xaml.cs 所做的更改,然后关闭文件。Save the changes to MainPage.xaml.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  9. 解决方案面板中,选择“Phoneword”项目,右键单击并选择“添加”>“新文件...”:In the Solution Pad, select the Phoneword project, right-click and select Add > New File...:

  10. 在“新建文件”对话框中,选择“常规”>“空类”,将新文件命名为 PhoneTranslator,然后单击“新建”按钮:In the New File dialog, select General > Empty Class, name the new file PhoneTranslator, and click the New button:

  11. 在“PhoneTranslator.cs”中,删除所有模板代码并将其替换为以下代码。In PhoneTranslator.cs, remove all of the template code and replace it with the following code. 此代码会将手机词翻译为电话号码:This code will translate a phone word to a phone number:

    using System.Text;
    
    namespace Phoneword
    {
        public static class PhonewordTranslator
        {
            public static string ToNumber(string raw)
            {
                if (string.IsNullOrWhiteSpace(raw))
                    return null;
    
                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);
                        // Bad character?
                        else
                            return null;
                    }
                }
                return newNumber.ToString();
            }
    
            static bool Contains(this string keyString, char c)
            {
                return keyString.IndexOf(c) >= 0;
            }
    
            static readonly string[] digits = {
                "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
            };
    
            static int? TranslateToNumber(char c)
            {
                for (int i = 0; i < digits.Length; i++)
                {
                    if (digits[i].Contains(c))
                        return 2 + i;
                }
                return null;
            }
        }
    }
    

    通过选择“文件”>“保存”,或按 ⌘ + S,保存对 PhoneTranslator.cs 所做的更改,然后关闭文件。Save the changes to PhoneTranslator.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  12. 解决方案面板中,选择“Phoneword”项目,右键单击并选择“添加”>“新文件...”:In the Solution Pad, select the Phoneword project, right-click and select Add > New File...:

  13. 在“新建文件”对话框中,选择“常规”>“空界面”,将新文件命名为 IDialer,然后单击“新建”按钮:In the New File dialog, select General > Empty Interface, name the new file IDialer, and click the New button:

  14. 在“IDialer.cs”中,删除所有模板代码并将其替换为以下代码。In IDialer.cs, remove all of the template code and replace it with the following code. 此代码将定义 Dial 方法,必须在每个平台上实现此方法,才可拨打翻译后的电话号码:This code defines a Dial method that must be implemented on each platform to dial a translated phone number:

    namespace Phoneword
    {
        public interface IDialer
        {
            bool Dial(string number);
        }
    }
    

    通过选择“文件”>“保存”,或按 ⌘ + S,保存对 IDialer.cs 所做的更改,然后关闭文件。Save the changes to IDialer.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

    备注

    此时完成了应用程序的常用代码。The common code for the application is now complete. 此时,可将特定于平台的电话拨号程序实现为 DependencyServicePlatform-specific phone dialer code will now be implemented as a DependencyService.

  15. 在“Solution Pad”中,选择“Phoneword.iOS”项目,右键单击并选择“添加”>“新建文件...”:In the Solution Pad, select the Phoneword.iOS project, right-click and select Add > New File...:

  16. 在“新建文件”对话框中,选择“常规”>“空类”,将新文件命名为 PhoneDialer,然后单击“新建”按钮:In the New File dialog, select General > Empty Class, name the new file PhoneDialer, and click the New button:

  17. 在“PhoneDialer.cs”中,删除所有模板代码并将其替换为以下代码。In PhoneDialer.cs, remove all of the template code and replace it with the following code. 此代码将创建 Dial 方法,此方法将在 iOS 平台上用于拨打翻译后的电话号码:This code creates the Dial method that will be used on the iOS platform to dial a translated phone number:

    using Foundation;
    using Phoneword.iOS;
    using UIKit;
    using Xamarin.Forms;
    
    [assembly: Dependency(typeof(PhoneDialer))]
    namespace Phoneword.iOS
    {
        public class PhoneDialer : IDialer
        {
            public bool Dial(string number)
            {
                return UIApplication.SharedApplication.OpenUrl (
                    new NSUrl ("tel:" + number));
            }
        }
    }
    

    通过选择“文件”>“保存”,或按 ⌘ + S,保存对 PhoneDialer.cs 所做的更改,然后关闭文件。Save the changes to PhoneDialer.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  18. 在“Solution Pad”中,选择“Phoneword.Droid”项目,右键单击并选择“添加”>“新建文件...”:In the Solution Pad, select the Phoneword.Droid project, right-click and select Add > New File...:

  19. 在“新建文件”对话框中,选择“常规”>“空类”,将新文件命名为 PhoneDialer,然后单击“新建”按钮:In the New File dialog, select General > Empty Class, name the new file PhoneDialer, and click the New button:

  20. 在“PhoneDialer.cs”中,删除所有模板代码并将其替换为以下代码。In PhoneDialer.cs, remove all of the template code and replace it with the following code. 此代码将创建 Dial 方法,此方法将在 Android 平台上用于拨打翻译后的电话号码:This code creates the Dial method that will be used on the Android platform to dial a translated phone number:

    using Android.Content;
    using Android.Telephony;
    using Phoneword.Droid;
    using System.Linq;
    using Xamarin.Forms;
    using Uri = Android.Net.Uri;
    
    [assembly: Dependency(typeof(PhoneDialer))]
    namespace Phoneword.Droid
    {
        public class PhoneDialer : IDialer
        {
            public bool Dial(string number)
            {
                var context = MainActivity.Instance;
                if (context == null)
                    return false;
    
                var intent = new Intent (Intent.ActionDial);
                intent.SetData (Uri.Parse ("tel:" + number));
    
                if (IsIntentAvailable (context, intent)) {
                    context.StartActivity (intent);
                    return true;
                }
    
                return false;
            }
    
            public static bool IsIntentAvailable(Context context, Intent intent)
            {
                var packageManager = context.PackageManager;
    
                var list = packageManager.QueryIntentServices (intent, 0)
                    .Union (packageManager.QueryIntentActivities (intent, 0));
    
                if (list.Any ())
                    return true;
    
                var manager = TelephonyManager.FromContext (context);
                return manager.PhoneType != PhoneType.None;
            }
        }
    }
    

    请注意,若要更好地理解此代码,需要使用最新 Android API。Note that this code assumes that you are using the latest Android API. 通过选择“文件”>“保存”,或按 ⌘ + S,保存对 PhoneDialer.cs 所做的更改,然后关闭文件。Save the changes to PhoneDialer.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  21. 在“Solution Pad”的“Phoneword.Droid”项目中,双击“MainActivity.cs”将其打开,然后删除所有模板代码并将其替换成下列代码:In the Solution Pad, in the Phoneword.Droid project, double click MainActivity.cs to open it, remove all of the template code and replace it with the following code:

    using Android.App;
    using Android.Content.PM;
    using Android.OS;
    
    namespace Phoneword.Droid
    {
        [Activity(Label = "Phoneword", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true,
                  ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
        public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
            internal static MainActivity Instance { get; private set; }
    
            protected override void OnCreate(Bundle bundle)
            {
                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
    
                base.OnCreate(bundle);
                Instance = this;
                global::Xamarin.Forms.Forms.Init(this, bundle);
                LoadApplication(new App());
            }
        }
    }
    

    选择“文件”>“保存”(或按 ⌘+S),保存对 MainActivity.cs 所做的更改,然后关闭文件。Save the changes to MainActivity.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  22. 在“Solution Pad”中,展开“属性”文件夹,然后右键单击“AndroidManifest.xml”文件:In the Solution Pad, expand the Properties folder and double-click the AndroidManifest.xml file:

  23. 在“所需的权限”部分中,启用“CallPhone”权限。In the Required permissions section, enable the CallPhone permission. 这将向应用程序授予进行电话呼叫的权限:This gives the application permission to place a phone call:

    通过选择“文件”>“保存”,或按 ⌘ + S,保存对 AndroidManifest.xml 所做的更改,然后关闭文件。Save the changes to AndroidManifest.xml by choosing File > Save (or by pressing ⌘ + S), and close the file.

  24. 在 Visual Studio for Mac 中,选择“生成”>“生成所有”菜单项,或按 ⌘ + BIn Visual Studio for Mac, select the Build > Build All menu item (or press ⌘ + B). 应用程序将生成,并在 Visual Studio for Mac 工具栏中显示一条成功消息。The application will build and a success message will appear in the Visual Studio for Mac toolbar.

  25. 如果发生错误,请重复前面的步骤并更正任何错误,直到成功生成应用程序。If there are errors, repeat the previous steps and correct any mistakes until the application builds successfully.

  26. 在 Visual Studio for Mac 工具栏中,按“开始”按钮(类似“播放”按钮的三角形按钮),启动 iOS 模拟器内的应用程序:In the Visual Studio for Mac toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside the iOS Simulator:

    注意:iOS 模拟器不支持电话呼叫。Note: phone calls are not supported in the iOS Simulator.

  27. 解决方案面板中,选择“Phoneword.Droid”项目,右键单击并选择“设为启动项目”:In the Solution Pad, select the Phoneword.Droid project, right-click and select Set As Startup Project:

  28. 在 Visual Studio for Mac 工具栏中,按“开始”按钮(类似“播放”按钮的三角形按钮),启动 Android 模拟器内的应用程序:In the Visual Studio for Mac toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside an Android emulator:

    警告

    Android Emulator 不支持电话呼叫。Phone calls are not supported in Android emulators.

祝贺你完成 Xamarin.Forms 应用程序。Congratulations on completing a Xamarin.Forms application. 本指南的下一个主题将回顾此演练中采用的步骤,以深入了解使用 Xamarin.Forms 开发应用程序的基础知识。The next topic in this guide reviews the steps that were taken in this walkthrough to gain an understanding of the fundamentals of application development using Xamarin.Forms.