close full screen of youtube player on back button android

Activity includes layout as below- Because the player is inside a com.google.android.youtube.player.YouTubePlayerSupportFragment, have to catch the back button with the correct behavior inside Activity:
<FrameLayout
        android:id="@+id/fl_youtubeFragment"
        android:visibility="visible"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <fragment
        android:id="@+id/youtube_player_fragment"
        android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    </FrameLayout>

@Override
public void onBackPressed() {
    if (fullScreen){
        videoPlayer.setFullscreen(false);
    } else{
        super.onBackPressed();
    }
}

Make sure that setOnFullscreenListener should be defined inside the onInitializationSuccess block.Otherwise it may give NullpointerException. Below code implements setOnFullscreenListener on onInitializationSuccess of  youTubePlayerFragment.
private void initializeYoutubePlayer() {
        youTubePlayerFragment = (YouTubePlayerSupportFragment) getSupportFragmentManager()
                .findFragmentById(R.id.youtube_player_fragment);
        if (youTubePlayerFragment == null)
            return;
        youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
                                                boolean wasRestored) {
                if (!wasRestored) {
                    youTubePlayer = player;//set the player style default
                    youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);

                    youTubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
                        @Override
                        public void onFullscreen(boolean _isFullScreen) {
                            fullScreen = _isFullScreen;
                        }
                        });
                    //cue the 1st video by default
                    youTubePlayer.cueVideo("2ycwSWSGcy0");
                }
            }

            @Override
            public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
                //print or show error if initialization failed
                Log.e(TAG, "Youtube Player View initialization failed");
            }
        });

    }

No comments:

Post a Comment

Popular Posts