是否可以在Xamarin Forms ContentView中嵌入Android.VideoView

时间:2019-01-31 23:07:19

标签: android forms xamarin 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?还是我对这种方法完全错误?

1 个答案:

答案 0 :(得分:2)

使用共享项目,您可以在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>

注意请勿在全局程序集级别或包含本机视图的XAML页面上启用 XamlCompilation,因为它将不起作用(并且没有在编译或运行时出现错误时,视图就不会显示出来,因为它们已被删除)...

MainActivity

[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

enter image description here输出: