.NET MAUI 安卓应用开发初体验

一、前言

.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.

.NET MAUI 安卓应用开发初体验

.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");
            });

DEBUG
builder.Logging.AddDebug();
if
        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实际没有生效,目前还没有找到原因。