首页 > 解决方案 > 是否可以在 Xamarin Forms ContentView 中嵌入 Android.VideoView

问题描述

我需要创建一个必须在 android 7.0 - 9.0 和最新的 iOS 上运行的移动应用程序

因此,在 Windows 10 上的 VS 2017 15.9.6 中,我尝试在共享项目中使用 Xamarin.Forms 3.4 作为原生 Android.VideoView 的容器。

我试图弄清楚如何做到这一点,因为 Mono.Android 示例不使用 Xamarin.Forms。那么,我是否需要在 xaml 文件中使用一种#ifdef 来嵌入 Android VideoView?还是我对这种方法完全错误?

标签: androidformsxamarinandroid-videoview

解决方案


使用共享项目,您可以在 XAML 中定义本机视图,然后在后面的代码中访问它们(这基本上是一项要求,因为本机 Android|iOS 控件不能直接绑定,并且大多数具有用于设置不可用功能的方法调用通过 XAML(即 VideoView 的.SetVideoURI方法没有基于 Xamarin 的包装器属性,因此您必须执行该方法才能播放视频)。

XAML:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    xmlns:androidWidget="clr-namespace:Android.Widget;assembly=Mono.Android;targetPlatform=Android"
    xmlns:androidGraphics="clr-namespace:Android.Graphics;assembly=Mono.Android;targetPlatform=Android"
    xmlns:androidContext="clr-namespace:Forms40Shared.Droid;assembly=Forms40Shared.Android;targetPlatform=Android"
    x:Class="Forms40Shared.NativeEmbedPage" >
    <ContentPage.Content>
        <StackLayout Margin="20">
            <androidWidget:TextView x:Arguments="{x:Static androidContext:MainActivity.Instance}" Text="Welcome to Forms!" TextSize="24" View.HorizontalOptions="Center" >
                <androidWidget:TextView.Typeface>
                    <androidGraphics:Typeface x:FactoryMethod="Create">
                        <x:Arguments>
                            <x:String>cursive</x:String>
                            <androidGraphics:TypefaceStyle>Normal</androidGraphics:TypefaceStyle>
                        </x:Arguments>
                    </androidGraphics:Typeface>
                </androidWidget:TextView.Typeface>
            </androidWidget:TextView>
            <ContentView x:Name="contentView" HorizontalOptions="FillAndExpand" VerticalOptions="Center" HeightRequest="200" >
                <androidWidget:VideoView x:Arguments="{x:Static androidContext:MainActivity.Instance}"  />
            </ContentView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

注意不要 XamlCompilation在全局程序集级别或包含本机视图的 XAML 页面上启用,因为它不起作用(并且在编译或运行时没有错误,视图只是不显示,因为它们已被剥离).. .

主要活动

[Activity(Label ~~~~
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    internal static MainActivity Instance { get; private set; }

    protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        Instance = this;

        ~~~
    }

代码背后:

#if __ANDROID__
            var videoView = (contentView as NativeViewWrapper).NativeView as VideoView;
            videoView.SetVideoURI(Android.Net.Uri.Parse($"android.resource://{Android.App.Application.Context.PackageName}/raw/fireplace"));
            videoView.Start();
#elif __IOS__
            ~~~
#endif

在此处输入图像描述输出:


推荐阅读