我可以使用cuePlaylist()
播放Youtube视频,但我也想允许用户点击任何列表项,然后我想用刚刚点击的视频用户刷新YoutubePlayerView
我正在使用cuePlaylist()
,因此将上一个和下一个按钮作为Youtube播放器的默认功能
那么,我可以使用在YoutubePlayerView
中选择的ListView
刷新YoutubePlayerView
吗?
这是我的完整代码,仍然是当我点击列表项中的任何一个时,Log
并没有发生任何变化,但是能够对ListView
视频ID进行更改,而我刚刚单击了ojit_code ...
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
strVideoID = flowerList.get(i).getUrl();
Log.d("url:", strVideoID); // getting particular video id
youTubePlayerFragment.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
// YouTubeプレーヤーの初期化成功
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
player.loadVideo(strVideoID);
player.play();
}
}
// YouTubeプレーヤーの初期化失敗
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult error) {
// YouTube error
String errorMessage = error.toString();
Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
Log.d("errorMessage:", errorMessage);
}
});
}
});
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.cuePlaylist(PLAYLIST_ID);
}
}
最佳答案
您在这里使用了错误的方法,您不需要每次都在YoutubePlayerFragment
上调用initialize,您只需在onCreate方法中完成第一个初始化就足够了
YouTubePlayerFragment youTubePlayerFragment = YouTubePlayerFragment.newInstance();
youTubePlayerFragment.initialize(API_KEY, this);
在Activity中实现的初始化监听器中,应将YoutubePlayer的引用保留在这样的类级别属性中
//your class level attribute to keep reference of player
YouTubePlayer mYoutubePlayer;
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.cuePlaylist(PLAYLIST_ID);
//Save reference of initialized player in class level attribute
mYoutubePlayer = youTubePlayer;
}
}
并使用此播放器属性在onItemClick内加载视频,而不是使用新的监听器在YoutubePlayerFragment上再次调用initialize
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
strVideoID = flowerList.get(i).getUrl();
Log.d("url:", strVideoID); // getting particular video id
if(mYoutubePlayer!=null){
mYoutubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
mYoutubePlayer.loadVideo(strVideoID);
mYoutubePlayer.play();
}
}
});