9

我正在尝试在我的片段中播放视频。但是,我无法让它工作。如果我要扩展“YoutubeFailureRecovery”,我会得到:

09-06 21:56:40.472: E/AndroidRuntime(4946): Caused by: java.lang.IllegalStateException: YouTubePlayerView 只能使用扩展 YouTubeBaseActivity 作为其上下文的 Activity 创建。

这是我的 .xml:

<com.google.android.youtube.player.YouTubePlayerView
    android:id="@+id/player"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

这是课程:

public class YoutubeFragment extends YoutubeFailureRecovery {

    YouTubePlayer player;
    YouTubePlayerView playerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle arg2) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.detailview, container, false);
    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        playerView = (YouTubePlayerView)getActivity().findViewById(R.id.player);
        playerView.initialize(DataHolder.DEVELOPER_KEY, this);

    }

    @Override
    public void onInitializationSuccess(Provider provider, YouTubePlayer player,
                                        boolean wasRestored) {
        // TODO Auto-generated method stub
        player.cueVideo("nCgQDjiotG0");
    }

    @Override
    protected Provider getYouTubePlayerProvider() {
        // TODO Auto-generated method stub
        return playerView;
    }
}


public abstract class YoutubeFailureRecovery extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener{

我只是不知道该怎么办。我尝试使用“YoutubePlayerSupportFragment”扩展我的 Fragment 类,尝试在 XML 中添加类似视频的片段,但没有任何效果(错误膨胀)。也许有人在 Fragment 中使用 YouTube API 有一些经验?

4

1 回答 1

28

YouTubePlayerView 仅适用于扩展 YouTubeBaseActivity 的 Activity。

如果你想使用 Fragments ,你必须使用 YoutubePlayerFragment / SupportFragment。

例如,您可以创建从 YoutubePlayerSupportFragment 继承的自定义片段:

public class VideoFragment extends YouTubePlayerSupportFragment {

    public VideoFragment() { }

    public static VideoFragment newInstance(String url) {

        VideoFragment f = new VideoFragment();

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

        f.setArguments(b);
        f.init();

        return f;
    }

    private void init() {

        initialize("yourapikey", new OnInitializedListener() {

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

            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
                if (!wasRestored) { 
                    player.cueVideo(getArguments().getString("url"));
                }
            }
        });
    }
}

在代码中它可能如下所示:

VideoFragment f = VideoFragment.newInstance("your-video-url");   
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, f).commit();

在这种情况下,“ fragment_container ”应该是一个空的FrameLayout

于 2013-09-06T19:50:55.013 回答