Viewpager中的YoutubePlayerSupportFragment

时间:2016-05-23 11:38:50

标签: android youtube-api

我有大约5个来自youtube的不同视频,我想将它们放入viewpager来滑动它们。有没有解释的解决方案,因为我在这里和不同的网站搜索,但找不到有用的东西。谢谢你的关注

1 个答案:

答案 0 :(得分:1)

切换ViewPager后,您必须在旧的YouTubePlayer上调用YouTubePlayerSupportFragment.reset(),然后YouTubePlayerSupportFragment.initialize()。这需要响应TabLayout的onTabSelected事件,这些事件无法使用.setupWithViewPager(吞下ViewPager和TabLayouts视图更改事件)。这大致是适配器所需要的(在响应选项卡更改时调用initialisePlayer和shutDownPlayer,在设置适配器,ViewPager和TabLayout的片段中):

private SparseArray<YouTubePlayerSupportFragment> fragments = new SparseArray<>(3);
private SparseArray<YouTubePlayer> players = new SparseArray<>(3);

@Override
public android.support.v4.app.Fragment getItem(final int position) {
YouTubePlayerSupportFragment fragment = new YouTubePlayerSupportFragment();
fragments.put(position, fragment);

return fragment;
}

public void initialisePlayer(final int position) {
YouTubePlayerSupportFragment fragment = fragments.get(position);
fragment.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(final YouTubePlayer.Provider provider, final YouTubePlayer youTubePlayer, final boolean b) {
players.put(position, youTubePlayer);
youTubePlayer.cueVideo(getVids()[position]);
}

@Override
public void onInitializationFailure(final YouTubePlayer.Provider provider, final YouTubeInitializationResult youTubeInitializationResult) {
}
});

}

public void shutDownPlayer(int position) {
YouTubePlayer player = players.get(position);
if (player == null) {
return;
}