i have created an android application that uses the youtube API however i am facing a problem. when I load a fragment with the youtube video. load another fragment then go back to the fragment with the youtube video the application is crashing.
Fragment that plays the video :
public static Fragment newInstance(Context context) {
WorkshopFragment f = new WorkshopFragment();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.workshop_fragment, null);
YouTubePlayerFragment youTubePlayerFragment = (YouTubePlayerFragment) getActivity().getFragmentManager().findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(API_KEY, this);
return root;
}
@Override
public void onInitializationFailure(Provider arg0,
YouTubeInitializationResult arg1) {
}
@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
}
layout :
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_below="@+id/paragraph"
android:layout_marginTop="30dp"
android:id="@+id/youtube_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Fixed Duplicate Id Error:
XML :
<FrameLayout
android:id="@+id/fragment_youtube"
android:layout_below="@+id/rule"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp" />
i then created the youtube fragment via code :
Fragment fragment = new YouTubePlayerFragment();
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_youtube, fragment);
ft.commit();
YouTubePlayerFragment youtubeFrag = (YouTubePlayerFragment) fragment;
youtubeFrag.initialize(API_KEY, this);