我想为 YouTube 播放器 API 添加一个 onClickListener 事件 我尝试了很多解决方案,但都没有用
我的一些尝试
YouTubePlayerView youTubePlayerView = findViewById(R.id.youtubePlayer);
youTubePlayerView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Log.d(TAG,"onClick");
}
});
YouTubePlayerView youTubePlayerView = findViewById(R.id.youtubePlayer);
youTubePlayerView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
Log.d(TAG,"onTouch");
return false;
}
});
此外,我尝试在 YouTube 播放器 View 上方添加一个布局并使其透明,然后向该布局添加一个点击监听器,但播放器每次都会在几秒钟后停止
我最后一次尝试使用 GestureDetector 类,但也没有成功
提前致谢
最佳答案
I tried to add a layout above the YouTube player view and make it transparent then add a click listener to this layout but the player stops after few seconds
YouTube Player API
不允许其上方的任何 View ,无论它是否可见,并将以 ErrorReason 关闭。 .
它还会消耗所有触摸事件而不共享它们。但是你可以Override
dispatchTouchEvent(MotionEvent)
父ViewGroup
方法到YouTubePlayerView
并窃取这些触摸事件以启动您自己的onClick()
回调。
您需要做的是,首先在放置 YouTubePlayerView
的 xml 布局文件中创建一个容器。
youtube_player_view_layout.xml
<MyCustomFrameLayout>
android:layout_width="match_parent"
android:layout_height="match_parent"
<YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</YouTubePlayerView>
</MyCustomFrameLayout>
MyCustomFrameLayout
必须在布局 xml 中添加完全限定名称,即 [my.class.package]+[ClassName]
MyCustomFrameLayout.java
public class MyCustomFrameLayout extends FrameLayout {
private boolean actionDownReceived = false;
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
actionDownReceived = true;
break;
}
case MotionEvent.ACTION_MOVE: {
// No longer a click, probably a gesture.
actionDownReceived = false;
break;
}
case MotionEvent.ACTION_UP: {
if (actionDownReceived) {
performClick();
}
break;
}
}
return super.dispatchTouchEvent(event);
}
}
然后您需要做的就是在 MyCustomFrameLayout
上设置点击监听器。
Disclaimer : The above code is not tested in an IDE and will probably not run correctly if/when copied as is. However the essence of the thought is properly projected here.
关于android - YouTubePlayer 的 onClickListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53983004/