每次方向更改时,只要使用所有子组件,就会重新创建活动。现在重要的部分是,YouTubePlayer.Provider将保存它的阶段(例如:加载的视频、当前播放位置和播放器配置)。看看以下内容:
YouTube 播放器概述
在您的情况下,方向更改后,只要其子片段(youTubePlayerFragment),就会重新创建活动。因此,您丢失了 YouTubePlayer 的即时引用和加载视频所需的数据(例如 videoID 或视频 url),但 YouTubePlayer 的提供者仍保持先前的状态,旋转后变为空。
解决方案:您实际上需要管理一种方法来保存在设备更改方向之前在 YouTubePlayer 上播放视频所需的数据,并在重新创建活动时检索数据。看看以下内容:
YouTubePlayerFragment 概述
不确定您的代码结构,但希望以下代码能给您一些想法:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("currentVideoID",videoID);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
videoID = savedInstanceState.getString("currentVideoID");
}
在 youtubeplayer 上播放视频的示例
private void loadYouTubePlayer(){
//load your youTubePlayerFragment here, i used YouTubePlayerSupportFragment(),may change in your case
//also you may not need to call getActivity(). Change the code as require
youTubePlayerFragment = (YouTubePlayerSupportFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(developerKey,new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
myYouTubePlayer = youTubePlayer;
myYouTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION | YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
myYouTubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
@Override
public void onFullscreen(boolean b) {
isFullScreenPlaying = b;
Log.d(null,"Now fullScreen");
}
});
if (!b) {
myYouTubePlayer.loadVideo(videoID);
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.e(null,"Initialization Failed !!!");
}
});
}