crash using YouTubePlayerSupportFragment

2019-07-29 22:41发布

I have an activity that extends from a fragment

public class Youtube_visor extends Fragment{ ...

and a method that creates a new YouTube player using YouTubePlayerSupportFragment

This is my code:

public void playVideo () {

        fragmentManager = getActivity().getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();

        YouTubePlayerSupportFragment player = new YouTubePlayerSupportFragment();
        fragmentTransaction.add(R.id.fragmentz, player); // fragmentz es un linearlayout que hay en el xml
        fragmentTransaction.commit();

        player.initialize(Static_generals.youtubeKey,new OnInitializedListener() {

            public void onInitializationSuccess(Provider arg0,
                    YouTubePlayer arg1, boolean arg2) {
                if (!arg2) {
                    arg1.cueVideo("3OhGkg_XT3o");
                }
            }

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

This works perfectly on the tablet, I have an activity with two fragments, left a list of videos, and right, the fragment which create the YouTube player

My problem is I do not want to create a new YouTubePlayer, I want to declare one in the xml and always use that. This is the fragment declared in the xml:

   <fragment
      android:name="com.google.android.youtube.player.YouTubePlayerFragment"
      android:id="@+id/youtube_fragment"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

Now, in my code, I replace this line:

YouTubePlayerSupportFragment player = new YouTubePlayerSupportFragment();

and put this new line:

YouTubePlayerSupportFragment player = (YouTubePlayerSupportFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.youtube_fragment);

but always crash. I searched for information about it but there is not much available, or have not found it :)

What am I doing wrong?

I guess I'm calling my fragment wrong, because when I do a new one working properly

I appreciate any help.

Thanks and kind regards

1条回答
2楼-- · 2019-07-29 23:16

Looks like you've put a YouTubePlayerFragment in your XML, but you're trying to cast it to a YouTubePlayerSupportFragment in the code. Try replacing this line:

android:name="com.google.android.youtube.player.YouTubePlayerFragment"

With this:

android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
查看更多
登录 后发表回答