2

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);
4

1 回答 1

0

由于片段是在 XML 中的,所以每次对 XML 进行扩充时,它都会生成一个新片段。而且我认为片段的 id 在 XML 中没有改变,它正在尝试创建具有相同 id 的新片段,因为已经有一个正在运行。两个正在运行的片段不能具有相同的 id,所以我认为应用程序崩溃了。

尝试在开始新片段之前杀死旧片段或以编程方式而不是通过 xml 创建片段。

于 2013-08-14T15:16:07.270 回答