问题
I am trying to embed a YouTubePlayerFragment into a DialogFragment. I am able to start the dialog one time and show the YouTubePlayer in it, but the second time it always crashes (no matter what I do). I think it is a lifecycle problem, which I simply don't understand. I am using AndroidAnnotations and the problem is that the view of the DialogFragment is always created in the onCreateView method, which is generated by AndroidAnnotations.
Does anyone know how to handle the lifecycle of a DialogFragment in this case?
This is the generated code from AndroidAnnotations:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
contentView_ = super.onCreateView(inflater, container, savedInstanceState);
if (contentView_ == null) {
contentView_ = inflater.inflate(layout.video_fragment, container, false);
}
return contentView_;
}
This is what I have so far:
public class VideoFragmentDialog extends DialogFragment implements YouTubePlayer.OnInitializedListener {
private static final String DEVELOPER_KEY = "secret";
private String videoUrl;
@FragmentById(R.id.youTubePlayerFragment)
YouTubePlayerFragment youTubePlayerFragment;
@AfterViews
void initializeYouTubePlayer() {
youTubePlayerFragment.setRetainInstance(true);
youTubePlayerFragment.initialize(DEVELOPER_KEY, this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer.cueVideo(videoUrl);
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
//To change body of implemented methods use File | Settings | File Templates.
}
public String getVideoUrl() {
return videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
}
This is the stacktrace:
Caused by: java.lang.IllegalArgumentException: Binary XML file line #10: Duplicate id 0x7f0a0281, tag null, or parent id 0x7f0a0280 with another fragment for com.google.android.youtube.player.YouTubePlayerFragment
at android.app.Activity.onCreateView(Activity.java:4248)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:673)
回答1:
I guess it's because you are using a fragment inside a fragment (Nested fragments) without using getChildFragment()
Look here for an example how to do it : nested fragments
来源:https://stackoverflow.com/questions/16870312/youtubeplayerfragment-lifecycle-in-a-dialogfragment