I want to add an onClickListener event for YouTube Player API I tried many many solutions but all of them didn't work
Some of my attempts
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;
}
});
Also, 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 every time
And my last attempt was working with GestureDetector class but also didn't work
Thank you in advance
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
does not allow any view above it be it a visible or not and will close with an ErrorReason.
It also consumes any and all touch events without sharing them. However you can Override
dispatchTouchEvent(MotionEvent)
method of the parent ViewGroup
to the YouTubePlayerView
and steal back these touch events to kick you own onClick()
callback.
What you have to do is, first create a container in the xml layout file where you've placed your YouTubePlayerView
.
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
must be added with fully qualified name in layout xml i.e. with [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);
}
}
and then all you need to do is set click listener on 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.