Search code examples
androidandroid-fragmentsandroid-youtube-api

View pager load off screen causing Fragement to load the wrong data


I have a view pager with offScreenLimit set to 5. inside each page there is a youtube player fragment. It works well however, it loads the video of the 5th page rather than the first.

If i am on page 1 it quickly loads page 1,2,3,4, then stays on 5. I need it to only load the video associated with the page i am on.

I think the problem is that I am creating the fragement wrong. every view on the pager is loading the correct data, except for the player fragment

Inside my view pager fragment

I am calling the method below from onCreateView()

public void loadPlayer(final String trailerUrl) {

    YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment
            .newInstance();
    getChildFragmentManager().beginTransaction()
            .replace(R.id.youtube_fragment, youTubePlayerFragment).commit();

        youTubePlayerFragment.initialize(Utils.DEVELOPER_KEY,
                new OnInitializedListener() {

                    @Override
                    public void onInitializationSuccess(Provider arg0,
                            YouTubePlayer player, boolean wasRestored) {
                        if (!wasRestored) {
                            player.cueVideo(trailerUrl);
                        }
                    }

                    @Override
                    public void onInitializationFailure(Provider arg0,
                            YouTubeInitializationResult errorReason) {
                    }

                });

}

Solution

  • I had the same problem and was able to solve it by using setUserVisibleHint(boolean isVisibleToUser) method in fragments. You should override this method and use it as indicator that your fragment is currently visible (if isVisibleToUser is true). So, if this method is invoked with isVisibleToUser==true, then you can invoke loadPlayer method.