Xamarin Android VideoView播放器控件无法跟踪播放器位置

时间:2019-07-18 13:46:04

标签: c# xamarin xamarin.android

我在Xamarin Forms应用程序中有一个ListView,视频播放器为ListViewItem。使用本机渲染器实现的视频播放器。效果很好,但是如果在显示播放器控件时移动视频播放器(滚动列表视图),则控件不会跟随播放器位置。

GIF

这是渲染器的某些部分。我不确定问题出在哪里,所以我不知道应该粘贴什么代码

public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, ARelativeLayout>
videoView = new VideoView(Context);
ARelativeLayout relativeLayout = new ARelativeLayout(Context);
relativeLayout.AddView(videoView);
ARelativeLayout.LayoutParams layoutParams =
new ARelativeLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
layoutParams.AddRule(LayoutRules.CenterInParent);
videoView.LayoutParameters = layoutParams;
videoView.Prepared += OnVideoViewPrepared;
SetNativeControl(relativeLayout);
mediaController = new MediaController(Context);
mediaController.SetMediaPlayer(videoView);
videoView.SetMediaController(mediaController);

1 个答案:

答案 0 :(得分:1)

这是一种解决方法:

在Droid项目中创建自定义MediaController:

class MyController : MediaController
{
    private Context _context;
    public MyController(Context context) : base(context)
    {
        _context = context;
    }
    private bool _isShowing { get; set; } = false;
    public override bool IsShowing { get { return _isShowing; } }

    public override void Show()
    {
        base.Show();
        _isShowing = true;

        ViewGroup parent = ((ViewGroup)this.Parent);
        parent.Visibility = ViewStates.Visible;
    }

    public override void Hide()
    {
        base.Hide();
        _isShowing = false;

       ViewGroup parent = ((ViewGroup)this.Parent);
        parent.Visibility = ViewStates.Gone;
    }
}

然后在您的 VideoPlayerRenderer 中,使用OnVideoViewPrepared方法设置MediaController:

private void OnVideoViewPrepared(object sender, EventArgs e)
    {
        MyController mc = new MyController(videoView.Context);
        videoView.SetMediaController(mc);
        FrameLayout f = (FrameLayout)mc.Parent;
        Android.Widget.RelativeLayout.LayoutParams lp = new Android.Widget.RelativeLayout.LayoutParams(
                Android.Widget.RelativeLayout.LayoutParams.MatchParent, Android.Widget.RelativeLayout.LayoutParams.WrapContent);
        lp.AddRule(LayoutRules.AlignParentBottom);
        ((LinearLayout)f.Parent).RemoveView(f);
        ((Android.Widget.RelativeLayout)videoView.Parent).AddView(f, lp);
        mc.SetAnchorView(videoView);
    }