Struggling with Youtube Player Support Fragment

帅比萌擦擦* 提交于 2019-11-27 12:31:17
CzarMatt

I ran into this problem before and I believe the issue stemmed from trying to inflate the YouTubePlayerSupportFragment layout. I solved my issue by creating a fragment like this:

public class PlayerYouTubeFrag extends YouTubePlayerSupportFragment {
    private String currentVideoID = "video_id";
    private YouTubePlayer activePlayer;

    public static PlayerYouTubeFrag newInstance(String url) {
        PlayerYouTubeFrag playerYouTubeFrag = new PlayerYouTubeFrag();

        Bundle bundle = new Bundle();
        bundle.putString("url", url);

        playerYouTubeFrag.setArguments(bundle);

        return playerYouTubeFrag;
    }

    private void init() {
        initialize(DeveloperKey.DEVELOPER_KEY, new OnInitializedListener() {

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

            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
                activePlayer = player;
                activePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
                if (!wasRestored) {
                    activePlayer.loadVideo(getArguments().getString("url"), 0);

                }
            }
        });
    }

    @Override
    public void onYouTubeVideoPaused() {
        activePlayer.pause();
    }
}

And then call an instance of the fragment like this:

PlayerYouTubeFrag myFragment = PlayerYouTubeFrag.newInstance("video_id");
getSupportFragmentManager().beginTransaction().replace(R.id.video_container, myFragment).commit();

Where video_container in my case was an empty frame layout.

Silmarilos

CzarMatt nailed it. Just to add to his answer though, don't forget you need to call the init() method. To do so follow CzarMatt's code and add one line:

public static PlayerYouTubeFrag newInstance(String url) {    
    PlayerYouTubeFrag playerYouTubeFrag = new PlayerYouTubeFrag();

    Bundle bundle = new Bundle();
    bundle.putString("url", url);

    playerYouTubeFrag.setArguments(bundle);

    playerYouTubeFrag.init(); //This line right here

    return playerYouTubeFrag;
}

Also, since I'm sure people will run into the same issue I did, even though CzarMatt mentioned it above, just to reiterate, when you pass in a URL for the video, you are NOT passing in the youtube URL

That is, with: "youtube.com/watch?v=z7PYqhABiSo&feature=youtu.be"

You are passing in only the video ID

I.e. use: "z7PYqhABiSo"

Since it is Google's own documentation, it knows how to play it just fine with the id.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!