将多个YoutubeFragments添加到View会导致同一视频被加载

时间:2017-04-16 13:35:04

标签: android youtube youtube-api youtube-data-api android-youtube-api

我有以下问题:
我想加载多个YouTube视频并在应用程序中显示它们。但是如果我使用(使用YouTubePlayerSupportFragment)创建多个Fragemnts,它只会加载我正在解析为片段的最后一个YouTube ID。
代码如下:

片段

public class YoutubeFragment extends Fragment {
private static final Long NUMBER_OF_VIDEOS_RETURNED = 30L;

YouTubePlayerSupportFragment youTubePlayerFragment;

public static YoutubeFragment newInstance(int index) {
    Bundle args = new Bundle();
    args.putInt("index", index);
    YoutubeFragment fragment = new YoutubeFragment();
    fragment.setArguments(args);
    return fragment;
}

public YouTubePlayerSupportFragment getYouTubePlayerFragment() {
    return youTubePlayerFragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.youtube_api, container, false);

    youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();

    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

    transaction.add(R.id.youtube_layout, youTubePlayerFragment).commit();

    youTubePlayerFragment.initialize(getString(R.string.api_key), new OnInitializedListener() {
        @Override
        public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
            if (!wasRestored) {
                Bundle arguments = getArguments();
                String videoId;
                if (arguments != null) {
                    videoId = arguments.getString("videoId");
                    player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
                    player.cueVideo(videoId);
                    System.out.println("Video with ID " + videoId + " has been created!");
                }
                //  player.loadVideo(VIDEO_ID);
                /*player.play();*/
            }
        }

        @Override
        public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
            // YouTube error
            String errorMessage = error.toString();
            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
            Log.d("errorMessage:", errorMessage);
        }
    });
    return rootView;
}

查看(在AsyncTask内):

private class initYTVideos extends AsyncTask<String, Void, List<String>> {

    @Override
    protected List<String> doInBackground(String... params) {
        try {
            // This object is used to make YouTube Data API requests. The last
            // argument is required, but since we don't need anything
            // initialized when the HttpRequest is initialized, we override
            // the interface and provide a no-op function.
            youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
                public void initialize(HttpRequest request) throws IOException {
                }
            }).setApplicationName(getString(R.string.application_id)).build();

            String channelId = getChannelId(MY_CHANNEL_NAME);

            YouTube.Search.List search = youtube.search().list("id,snippet");
            search.setKey(getString(R.string.api_key));
            search.setChannelId(channelId);
            search.setType("video");

        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
            search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);

            SearchListResponse searchResponse = search.execute();
            List<SearchResult> searchResultList = searchResponse.getItems();
            if (searchResultList != null) {
                prettyPrint(searchResultList.iterator(), channelId);
            }
        } catch (GoogleJsonResponseException e) {
            System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                    + e.getDetails().getMessage());
        } catch (IOException e) {
            System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return videoIds;
    }

    @Override
    protected void onPostExecute(List<String> result) {
        for (String s : result) {
            System.out.println(s);
        }
        YoutubeFragment firstYoutubeFragment = YoutubeFragment.newInstance(1);
        Bundle firstBundle = new Bundle();
        firstBundle.putString("videoId", result.get(5));
        firstYoutubeFragment.setArguments(firstBundle);

        YoutubeFragment secondYoutubeFragment = YoutubeFragment.newInstance(2);
        Bundle secondBundle = new Bundle();
        secondBundle.putString("videoId", result.get(7));
        secondYoutubeFragment.setArguments(secondBundle);

        FragmentManager manager = getSupportFragmentManager();

        FragmentTransaction ft = manager.beginTransaction();
        ft.add(R.id.my_videos, firstYoutubeFragment, "frag1");
        ft.add(R.id.my_videos, secondYoutubeFragment, "frag2");
        ft.commit();
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

我真的不知道我做错了什么......我真的希望有人可以帮助我!欢迎任何解决方法!

2 个答案:

答案 0 :(得分:1)

首先,感谢Teyam的研究。
我最终得到了以下解决方案:
https://androidtutorialmagic.wordpress.com/my-mini-project/multiple-youtube-video-in-recyclerviewlistview-in-android/这真的很棒!
它易于实现且可以很好地定制。

答案 1 :(得分:0)

AFAIK,目前不支持此功能。

您可能需要查看这些SO帖子中建议的解决方案:

希望有所帮助!