Search code examples
androidvideoyoutube-apiandroid-youtube-api

YouTubePlayerFragment black screen on orientation changes


I'm trying to keep playing YouTubePlayerFragment on orientation changes.

the code looks like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
    FrameLayout frameLayout = new FrameLayout(getActivity());
    populateViewForOrientation(inflater, frameLayout);
    return frameLayout;
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    LayoutInflater inflater = LayoutInflater.from(getActivity());
    populateViewForOrientation(inflater, (ViewGroup) getView());
}

private void populateViewForOrientation(LayoutInflater inflater, ViewGroup viewGroup) {
    viewGroup.removeAllViewsInLayout();
    rootView = inflater.inflate(getLayoutResId(), viewGroup);
    ButterKnife.bind(this, rootView);

    if (frYTube != null) {
       FragmentTransaction transaction = getFragmentManager().beginTransaction();
       transaction.replace(R.id.frame, frYTube);
       transaction.commitAllowingStateLoss();
    }
}

fragment replaced (i see text on it) and the music is playing but instead of video - black screen. How can i deal with it? is it possible to get video back? btw, if after rotation next video is oppenes - the video appears. i've tried to call pause and play for current video - it dosen't help. i haven't try YouTubePlayerView because i use moxy so i need to deal with fragment.

upd

it looks like to create custom view with YouTubePlayerFragment inside have more stable behavior (and remove add view then). but the black screen problem still exists.

it's possible to restore video in this case with:

 mYouTubePlayer.loadVideo(url);
 ...
 public void onLoaded(String s) {
  mYouTubePlayer.seekToMillis(mills);

but there is no sense too reload video, i'm trying to avoid this - the delay appears


Solution

  • Only way i found and it works is to handle screen orientation manually:

    1) add to your activity:

    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    

    2) in activity class:

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
       super.onConfigurationChanged(newConfig);
       someFunctionToHandleOrienttion();
    }
    

    and you shouldn't inflate new layout. just remove and recreate/add all you need except youtubeframe to make land layout looks you want. it's a bit tricky and strange, but in other cases you got black screen instead video.