首页 > 解决方案 > Xamarin CarouselView 错误:膨胀类 CarouselView 时出错

问题描述

我正在尝试使用 CarouselView 创建一个水平 ListView,因为我的一个客户不喜欢我在他们的项目中实现的垂直 ListView。我尝试遵循几个教程,但无济于事。

我有一种预感,问题在于我下载的 nuget 包或我在 xml 中使用的命名空间。我在 Xamarin Android 应用程序中使用 Visual Studio 2019。

这是我为轮播视图下载的 nuget 包列表:

轮播视图

CarouselView.FormsPlugin

CarouselView.FormsPlugin.Fix

Xamarin.Forms v5.0.0.2083

这是我的 content_main.xml 中的代码

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:forms="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:showIn="@layout/activity_main">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="Hello World!" />
    
        <forms:CarouselView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    
    </RelativeLayout>

除了您在创建新项目时获得的默认页面之外,我在此处添加的所有内容是要使用的命名空间的 xmlns:forms 行和 CarouselView 标记本身。

在 OnCreate 后面的代码中,我有这个:

                base.OnCreate(savedInstanceState);
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
                CarouselViewRenderer.Init();
    
                SetContentView(Resource.Layout.activity_main);

同样,我在这里添加的只是 CarouselViewRenderer 上的 Init 调用。调用 SetContentView 时,我收到错误“Error inflating class CarouselView”。

如果我忽略了一些愚蠢的事情,请告诉我。我无法让 Intellisense 在 xml 中建议 CarouselView,所以我确定有问题。也许它找不到标签?这就是为什么我认为这可能是一个命名空间问题。

我尝试了什么:

我尝试交换 Init 调用并以不同的顺序调用它,但没有任何效果。

我在 GitHub 论坛中寻找类似的问题,但似乎没有解决方案适用于我的案例。

我尝试将 xml 中的标签名称更改为不带“w”的 CarouselVie 之类的名称,但我得到了同样的错误,这意味着它可能没有找到该标签的开头。

我尝试更改命名空间并寻找要下载的不同 nuget 包,但仍然没有任何效果。

标签: c#xamarinxamarin.formsxamarin.androidxamarin.forms.carouselview

解决方案


来自文档什么是 Xamarin.Forms?,我们知道

Xamarin.Forms 是一个开源 UI 框架。Xamarin.Forms 允许开发人员从单个共享代码库构建 Xamarin.Android、Xamarin.iOS 和 Windows 应用程序。

Xamarin.Forms 允许开发人员使用 C# 中的代码隐藏在 XAML 中创建用户界面。这些接口在每个平台上都呈现为高性能本机控件。

在运行时,Xamarin.Forms 利用平台呈现器将跨平台 UI 元素转换为 Xamarin.Android、Xamarin.iOS 和 UWP 上的本机控件。这使开发人员能够获得原生的外观、感觉和性能,同时实现跨平台代码共享的好处。

因此,您可以在表单的应用程序中使用 Xamarin Forms 控件 ( CarouselView),并将应用程序部署到您的 android 设备或 ios 设备。

从您发布的上述描述中,我认为您对CarouselView' 的用法感到困惑。

由于CarouselView是 xamarin 表单的控件,因此您应该在 xamarin 表单的应用程序中使用它,而不是在 Android 中引用它。

使用方法CarouselView可以参考官方文档:Xamarin.Forms CarouselView

本文档中包含一个示例(Xamarin.Forms - CarouselView),您可以下载它并将其部署到您的 android 设备上,这将帮助您更好地理解它。


推荐阅读