Reputation: 5739
I'd like to use a fragment inside a dialog as well as inside an activity. Therefore the fragment was derived from DialogFragment
.
Now the problem is, as soon as the fragment overwrites both onCreateView()
and onCreateDialog()
methods, displaying the fragment as a dialog crashes with android.util.AndroidRuntimeException: requestFeature() must be called before adding content
.
If onCreateView()
gets removed, displaying as a dialog works well, but embedding the fragment in an activity, crashes with java.lang.IllegalStateException: Fragment com.blah.SomeFragment did not create a view.
Removing onCreateDialog()
would be a solution, but where should the dialogs buttons then be wired up?
Now I'm completely puzzled how to use the same DialogFragment
derived class in both scenarios - inside a dialog and inside an activity - isn't that what DialogFragment
is all about? I kinda don't get it... What's the right way to use DialogFragment
?
Upvotes: 0
Views: 641
Reputation: 1025
If you need your DialogFragment to work both as a DialogFragment and a normal fragment inside other activities, you can can use setShowsDialog
to specify which you are using, like so:
@Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setShowsDialog( false );
}
and then override onCreateDialog
and onCreateView
like this:
@NonNull
@Override
public Dialog onCreateDialog( Bundle savedInstanceState ) {
AlertDialog.Builder builder = new Builder( getActivity() );
// custom view inside the dialog
builder.setView( createView( getActivity().getLayoutInflater(), null, savedInstanceState ) );
return builder.create();
}
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
if ( getShowsDialog() ) {
return super.onCreateView( inflater, container, savedInstanceState );
} else {
// custom view creation
return createView( inflater, container, savedInstanceState );
}
}
In my code, I have one BaseClassFragment
that setsShowDialog false, and then I have a subclass, DialogBaseClassFragment
, that setsShowDialog to true and use them as appropriate.
Upvotes: 1