.NET MAUI 安卓應用開發初體驗

徐業貴發表於2022-11-25

一、.NET MAUI開發環境搭建&安卓SDK和安卓模擬器安裝提示網路連線失敗問題解決

引言

本節目標是幫助第一次搭建.NET MAUI開發環境,在下載安卓SDK和安卓模擬器過程中一直提示網路問題解決思路。

現象一:Visiual Studio 2022中新增Android裝置管理時,提示系統映像下載錯誤:Network is not reachable. Please check your connection and try again.

.NET MAUI 安卓應用開發初體驗

現象二:Visiual Studio 2022中新增Android SDK和工具時,提示"網路不可用。請檢查你的連線,然後再重試"

.NET MAUI 安卓應用開發初體驗

.NET MAUI 簡介

官方文件

什麼是 .NET MAUI? - .NET MAUI | Microsoft Learn

.NET Multi-platform App UI (.NET MAUI) is a cross-platform framework for creating native mobile and desktop apps with C# and XAML.

Using .NET MAUI, you can develop apps that can run on Android, iOS, macOS, and Windows from a single shared code-base.

image

.NET MAUI 全稱 .NET Multi-platform App UI

開發環境介紹

VS版本:Microsoft Visual Studio Community 2022 (64 位) - Current 版本 17.4.1

.NET 版本:.NET 7.0 STS

安裝【 .NET Multi-platform App UI 開發】

.NET MAUI 安卓應用開發初體驗

Android SDK 和 安卓模擬器

這裡直接介紹出現網路問題後,解決方案

1、檢視VS中 Android SDK 儲存位置
.NET MAUI 安卓應用開發初體驗
2、安裝 JAVA JDK,並配置在系統環境中JAVA_HOME (可以選擇JDK11或者JDK 8.0)

3、下載並安裝 Android Studio

4、啟動Android Studio,設定國內映象

映象地址:http://mirrors.neusoft.edu.cn/

.NET MAUI 安卓應用開發初體驗 .NET MAUI 安卓應用開發初體驗

5、設定 Android SDK 儲存位置,將Android Studio 中SDK 儲存位置 和 VS 中一樣

.NET MAUI 安卓應用開發初體驗

6、下載對應的Android SDK 和 Android Emulator

.NET MAUI 安卓應用開發初體驗

7、透過AVD Manager新建安卓模擬裝置
.NET MAUI 安卓應用開發初體驗

二、第一個.NET MAUI 安卓應用程式

跟著官方文件,開啟第一個.NET MAUI 程式

新建一個.NET MAUI應用程式

.NET MAUI 安卓應用開發初體驗

執行效果

.NET MAUI 安卓應用開發初體驗

專案截圖

.NET MAUI 安卓應用開發初體驗

MainViewModel

新建ViewModel資料夾,新增MainViewModel類,繼承ObservableObject。透過NuGet新增CommunityToolkit.Mvvm 8.1.0-preview1 依賴項。

  public partial class MainViewModel : ObservableObject
    {
        public MainViewModel()
        {
            this.Items= new ObservableCollection<string>();
        }
        [ObservableProperty]
        public string inputText;

        [ObservableProperty]
        public ObservableCollection<string> items;

        [RelayCommand]
        public void Add()
        {
            if (!string.IsNullOrWhiteSpace(InputText))
            {
                Items.Add(InputText);
                InputText = string.Empty;
            }
        }

        [RelayCommand]
        public void Remove(string item)
        {
            if (Items.Contains(item))
            {
                Items.Remove(item);
            }
        }
    }

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiAppMvvM.MainPage"
             xmlns:viewModel="clr-namespace:MauiAppMvvM.ViewModel"
             x:DataType="viewModel:MainViewModel"
             x:Name="mainPage">

    <Grid RowDefinitions="100, Auto, *"
          ColumnDefinitions=".75*, .25*"
          Padding="10" 
          RowSpacing="10"
          ColumnSpacing="10">

        <Image Grid.ColumnSpan="2"
               Source="dotnet_bot.svg"  
               BackgroundColor="Orange"/>

        <Entry Placeholder="請輸入您的任務項"
               Grid.Row="1"
               Grid.Column="0"
               Keyboard="Chat"
               Text ="{Binding InputText}"/>

        <Button Text="Add"
                Grid.Row="1"
                Grid.Column="1"
                Command="{Binding AddCommand}" />


        <CollectionView Grid.Row="2"
                        Grid.ColumnSpan="2"
                        ItemsSource="{Binding Items}">
            <CollectionView.ItemTemplate >
                <DataTemplate x:DataType="{x:Type x:String}">
                    <SwipeView>
                        <SwipeView.RightItems>
                            <SwipeItem Text="Delete" 
                                       IconImageSource="delete.png"
                                       BackgroundColor="LightPink" 
                                       Command="{Binding Source={RelativeSource AncestorType={x:Type viewModel:MainViewModel}}, Path=RemoveCommand}"
                                       CommandParameter="{Binding .}"/>
                        </SwipeView.RightItems>
                        <Grid Padding="0,5">
                            <Frame>
                                <Label Text="{Binding .}"
                                       FontSize="24"/>
                            </Frame>
                        </Grid>
                    </SwipeView>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </Grid>
</ContentPage>

MainPage.xaml.cs

  public MainPage(MainViewModel viewModel)
  {
       	 InitializeComponent();
         this.BindingContext = viewModel;
   }

MauiProgram.cs

  public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                    fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                });

#if DEBUG
		builder.Logging.AddDebug();
#endif
            builder.Services.AddSingleton<MainPage>();
            builder.Services.AddSingleton<ViewModel.MainViewModel>();
            
            return builder.Build();
        }
    }

至此,一個完整的.NET MAUI完成了,讓我們一起享受.NET MAUI之旅吧!

後記

 <SwipeItem Text="Delete" 
            IconImageSource="delete.png"
            BackgroundColor="LightPink" 
            Command="{Binding Source={RelativeSource AncestorType={x:Type viewModel:MainViewModel}}, Path=RemoveCommand}"
            CommandParameter="{Binding .}"/>

SwipeItem的Command實際沒有生效,目前還沒有找到原因

相關文章