close fullscreen of Youtube Player on back button inside fragment
Just to add to Andre's reply.
In your parent Activity add:
public YouTubePlayer youTubePlayer;
public boolean isYouTubePlayerFullScreen;
In your fragment add:
MainActivity mainActivity = (MainActivity) getActivity();
Then, on YouTubePlayerFragment
initialization:
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean b) {
mainActivity.youTubePlayer = player;
player.loadVideo(videoId);
player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
@Override
public void onFullscreen(boolean b) {
mainActivity.isYouTubePlayerFullScreen = b;
}
});
}
Now your Activity
has access to YouTubePlayer
and information if player is full screen or not.
Next, inside your Activity
, override onBackPressed
like this:
@Override
public void onBackPressed() {
if (youTubePlayer != null && isYouTubePlayerFullScreen){
youTubePlayer.setFullscreen(false);
} else {
super.onBackPressed();
}
}
You can override onBackPressed()
in your activity and in case your player is in fullscreen, you can handle it there as follows:
@Override
public void onBackPressed() {
if (youtubePlayer != null && isFullscreen) {
// if fullscreen, set fullscreen false
youtubePlayer.setFullscreen(false);
} else {
// if NOT fullscreen, perform default call on back press
super.onBackPressed();
}
}
P.S. In above code fragment,
isFullscreen
is instance variable of our activity and is synced withyoutubePlayer
state from withinOnFullscreenListener
set onyoutubePlayer.setOnFullScreenListener()
.Hope that makes sense :)