DialogFragment
public class DialogFragment extends Fragment implements DialogInterface.OnCancelListener, DialogInterface.OnDismissListener
AppCompatDialogFragment |
A special version of |
MediaRouteChooserDialogFragment |
Media route chooser dialog fragment. |
MediaRouteControllerDialogFragment |
Media route controller dialog fragment. |
PreferenceDialogFragmentCompat |
Abstract base class which presents a dialog associated with a |
A fragment that displays a dialog window, floating in the foreground of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the APIs here, not with direct calls on the dialog.
Implementations should override this class and implement onViewCreated to supply the content of the dialog. Alternatively, they can override onCreateDialog to create an entirely custom dialog, such as an AlertDialog, with its own content.
Topics covered here:
Lifecycle
DialogFragment does various things to keep the fragment's lifecycle driving it, instead of the Dialog. Note that dialogs are generally autonomous entities -- they are their own window, receiving their own input events, and often deciding on their own when to disappear (by receiving a back key event or the user clicking on a button).
DialogFragment needs to ensure that what is happening with the Fragment and Dialog states remains consistent. To do this, it watches for dismiss events from the dialog and takes care of removing its own state when they happen. This means you should use show, show, or showNow to add an instance of DialogFragment to your UI, as these keep track of how DialogFragment should remove itself when the dialog is dismissed.
Basic Dialog
The simplest use of DialogFragment is as a floating container for the fragment's view hierarchy. A simple implementation may look like this:
public class MyDialogFragment extends DialogFragment { int mNum; // Create a new instance of MyDialogFragment, providing "num" as an argument. static MyDialogFragment newInstance(int num) { MyDialogFragment f = new MyDialogFragment(); // Supply num input as an argument. Bundle args = new Bundle(); args.putInt("num", num); f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNum = getArguments().getInt("num"); // Pick a style based on the num. int style = DialogFragment.STYLE_NORMAL, theme = 0; switch ((mNum-1)%6) { case 1: style = DialogFragment.STYLE_NO_TITLE; break; case 2: style = DialogFragment.STYLE_NO_FRAME; break; case 3: style = DialogFragment.STYLE_NO_INPUT; break; case 4: style = DialogFragment.STYLE_NORMAL; break; case 5: style = DialogFragment.STYLE_NORMAL; break; case 6: style = DialogFragment.STYLE_NO_TITLE; break; case 7: style = DialogFragment.STYLE_NO_FRAME; break; case 8: style = DialogFragment.STYLE_NORMAL; break; } switch ((mNum-1)%6) { case 4: theme = android.R.style.Theme_Holo; break; case 5: theme = android.R.style.Theme_Holo_Light_Dialog; break; case 6: theme = android.R.style.Theme_Holo_Light; break; case 7: theme = android.R.style.Theme_Holo_Light_Panel; break; case 8: theme = android.R.style.Theme_Holo_Light; break; } setStyle(style, theme); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_dialog, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // set DialogFragment title getDialog().setTitle("Dialog #" + mNum); } }
An example showDialog() method on the Activity could be:
public void showDialog() {
mStackLevel++;
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
newFragment.show(ft, "dialog");
}This removes any currently shown dialog, creates a new DialogFragment with an argument, and shows it as a new state on the back stack. When the transaction is popped, the current DialogFragment and its Dialog will be destroyed, and the previous one (if any) re-shown. Note that in this case DialogFragment will take care of popping the transaction of the Dialog that is dismissed separately from it.
Alert Dialog
Instead of (or in addition to) implementing onViewCreated to generate the view hierarchy inside of a dialog, you may implement onCreateDialog to create your own custom Dialog object.
This is most useful for creating an AlertDialog, allowing you to display standard alerts to the user that are managed by a fragment. A simple example implementation of this is:
public static class MyAlertDialogFragment extends DialogFragment { public static MyAlertDialogFragment newInstance(int title) { MyAlertDialogFragment frag = new MyAlertDialogFragment(); Bundle args = new Bundle(); args.putInt("title", title); frag.setArguments(args); return frag; } @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setIcon(R.drawable.alert_dialog_icon) .setTitle(title) .setPositiveButton(R.string.alert_dialog_ok, (dialogInterface, i) -> ((MainActivity)getActivity()).doPositiveClick()) .setNegativeButton(R.string.alert_dialog_cancel, (dialogInterface, i) -> ((MainActivity)getActivity()).doNegativeClick()) .create(); return super.onCreateDialog(savedInstanceState); } }
The activity creating this fragment may have the following methods to show the dialog and receive results from it:
void showDialog() {
DialogFragment newFragment = MyAlertDialogFragment.newInstance(
R.string.alert_dialog_two_buttons_title);
newFragment.show(getSupportFragmentManager(), "dialog");
}
public void doPositiveClick() {
// Do stuff here.
Log.i("MainActivity", "Positive click!");
}
public void doNegativeClick() {
// Do stuff here.
Log.i("MainActivity", "Negative click!");
}Note that in this case the fragment is not placed on the back stack, it is just added as an indefinitely running fragment. Because dialogs normally are modal, this will still operate as a back stack, since the dialog will capture user input until it is dismissed. When it is dismissed, DialogFragment will take care of removing itself from its fragment manager.
Selecting Between Dialog or Embedding
A DialogFragment can still optionally be used as a normal fragment, if desired. This is useful if you have a fragment that in some cases should be shown as a dialog and others embedded in a larger UI. This behavior will normally be automatically selected for you based on how you are using the fragment, but can be customized with setShowsDialog.
For example, here is a simple dialog fragment:
public static class MyDialogFragment extends DialogFragment { static MyDialogFragment newInstance() { return new MyDialogFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // this fragment will be displayed in a dialog setShowsDialog(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.hello_world, container, false); View tv = v.findViewById(R.id.text); ((TextView)tv).setText("This is an instance of MyDialogFragment"); return v; } }
An instance of this fragment can be created and shown as a dialog:
void showDialog() {
// Create the fragment and show it as a dialog.
DialogFragment newFragment = MyDialogFragment.newInstance();
newFragment.show(getSupportFragmentManager(), "dialog");
}It can also be added as content in a view hierarchy:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); DialogFragment newFragment = MyDialogFragment.newInstance(); ft.add(R.id.embedded, newFragment); ft.commit();
Summary
Constants |
|
|---|---|
static final int |
STYLE_NORMAL = 0Style for |
static final int |
STYLE_NO_FRAME = 2Style for |
static final int |
STYLE_NO_INPUT = 3Style for |
static final int |
STYLE_NO_TITLE = 1Style for |
Public constructors |
|---|
|
Constructor used by the default |
DialogFragment(@LayoutRes int contentLayoutId)Alternate constructor that can be called from your default, no argument constructor to provide a default layout that will be inflated by |
Public methods |
|
|---|---|
void |
dismiss()Dismiss the fragment and its dialog. |
void |
Version of |
void |
|
@Nullable Dialog |
Return the |
boolean |
Return the current value of |
@StyleRes int |
getTheme() |
boolean |
Return the current value of |
void |
@MainThreadThis method is deprecated. use |
void |
@MainThreadCalled when a fragment is first attached to its context. |
void |
onCancel(@NonNull DialogInterface dialog) |
void |
@MainThreadCalled to do initial creation of a fragment. |
@NonNull Dialog |
@MainThreadOverride to build your own custom Dialog container. |
void |
Remove dialog. |
void |
Called when the fragment is no longer attached to its activity. |
void |
@CallSuper |
@NonNull LayoutInflater |
onGetLayoutInflater(@Nullable Bundle savedInstanceState)Returns the LayoutInflater used to inflate Views of this Fragment. |
void |
@MainThreadCalled to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. |
void |
Called when the Fragment is visible to the user. |
void |
Called when the Fragment is no longer started. |
void |
@MainThreadCalled when all saved state has been restored into the view hierarchy of the fragment. |
final @NonNull ComponentDialog |
Return the |
final @NonNull Dialog |
Return the |
void |
setCancelable(boolean cancelable)Control whether the shown Dialog is cancelable. |
void |
setShowsDialog(boolean showsDialog)Controls whether this fragment should be shown in a dialog. |
void |
Call to customize the basic appearance and behavior of the fragment's dialog. |
void |
show(@NonNull FragmentManager manager, @Nullable String tag)Display the dialog, adding the fragment to the given FragmentManager. |
int |
show(@NonNull FragmentTransaction transaction, @Nullable String tag)Display the dialog, adding the fragment using an existing transaction and then |
void |
showNow(@NonNull FragmentManager manager, @Nullable String tag)Display the dialog, immediately adding the fragment to the given FragmentManager. |
Inherited methods |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Constants
STYLE_NORMAL
public static final int STYLE_NORMAL = 0
Style for setStyle: a basic, normal dialog.
STYLE_NO_FRAME
public static final int STYLE_NO_FRAME = 2
Style for setStyle: don't draw any frame at all; the view hierarchy returned by onCreateView is entirely responsible for drawing the dialog.
STYLE_NO_INPUT
public static final int STYLE_NO_INPUT = 3
Style for setStyle: like STYLE_NO_FRAME, but also disables all input to the dialog. The user can not touch it, and its window will not receive input focus.
STYLE_NO_TITLE
public static final int STYLE_NO_TITLE = 1
Style for setStyle: don't include a title area.
Public constructors
DialogFragment
public DialogFragment()
Constructor used by the default FragmentFactory. You must set a custom FragmentFactory if you want to use a non-default constructor to ensure that your constructor is called when the fragment is re-instantiated.
It is strongly recommended to supply arguments with setArguments and later retrieved by the Fragment with getArguments. These arguments are automatically saved and restored alongside the Fragment.
Applications should generally not implement a constructor. Prefer onAttach instead. It is the first place application code can run where the fragment is ready to be used - the point where the fragment is actually associated with its context.
DialogFragment
public DialogFragment(@LayoutRes int contentLayoutId)
Alternate constructor that can be called from your default, no argument constructor to provide a default layout that will be inflated by onCreateView.
class MyDialogFragment extends DialogFragment { public MyDialogFragment() { super(R.layout.dialog_fragment_main); } }
set a custom FragmentFactory if you want to use a non-default constructor to ensure that your constructor is called when the fragment is re-instantiated.
| See also | |
|---|---|
DialogFragment |
|
onCreateView |
Public methods
dismiss
public void dismiss()
Dismiss the fragment and its dialog. If the fragment was added to the back stack, all back stack state up to and including this entry will be popped. Otherwise, a new transaction will be committed to remove the fragment.
dismissAllowingStateLoss
public void dismissAllowingStateLoss()
Version of dismiss that uses FragmentTransaction.commitAllowingStateLoss(). See linked documentation for further details.
dismissNow
@MainThread
public void dismissNow()
Version of dismiss that uses commitNow. See linked documentation for further details.
getDialog
public @Nullable Dialog getDialog()
Return the Dialog this fragment is currently controlling.
| See also | |
|---|---|
requireDialog |
getShowsDialog
public boolean getShowsDialog()
Return the current value of setShowsDialog.
isCancelable
public boolean isCancelable()
Return the current value of setCancelable.
onActivityCreated
@MainThread
public voidonActivityCreated(@Nullable Bundle savedInstanceState)
Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use #setRetainInstance(boolean) to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after #onCreateView and before #onViewStateRestored(Bundle).
onAttach
@MainThread
public void onAttach(@NonNull Context context)
Called when a fragment is first attached to its context. onCreate will be called after this.
onCreate
@MainThread
public void onCreate(@Nullable Bundle savedInstanceState)
Called to do initial creation of a fragment. This is called after onAttach and before onCreateView.
Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, add a androidx.lifecycle.LifecycleObserver on the activity's Lifecycle, removing it when it receives the CREATED callback.
Any restored child fragments will be created before the base Fragment.onCreate method returns.
onCreateDialog
@MainThread
public @NonNull Dialog onCreateDialog(@Nullable Bundle savedInstanceState)
Override to build your own custom Dialog container. This is typically used to show an AlertDialog instead of a generic Dialog; when doing so, onCreateView does not need to be implemented since the AlertDialog takes care of its own content.
This method will be called after onCreate and immediately before onCreateView. The default implementation simply instantiates and returns a Dialog class.
Note: DialogFragment own the Dialog.setOnCancelListener and Dialog.setOnDismissListener callbacks. You must not set them yourself. To find out about these events, override onCancel and onDismiss.
onDetach
@MainThread
public void onDetach()
Called when the fragment is no longer attached to its activity. This is called after onDestroy.
onGetLayoutInflater
public @NonNull LayoutInflater onGetLayoutInflater(@Nullable Bundle savedInstanceState)
Returns the LayoutInflater used to inflate Views of this Fragment. The default implementation will throw an exception if the Fragment is not attached.
If this is called from within onCreateDialog, the layout inflater from onGetLayoutInflater, without the dialog theme, will be returned.
onSaveInstanceState
@MainThread
public void onSaveInstanceState(@NonNull Bundle outState)
Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. If a new instance of the fragment later needs to be created, the data you place in the Bundle here will be available in the Bundle given to onCreate, onCreateView, and onViewCreated.
This corresponds to Activity.onSaveInstanceState(Bundle) and most of the discussion there applies here as well. Note however: this method may be called at any time before onDestroy. There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.
onStart
@MainThread
public void onStart()
Called when the Fragment is visible to the user. This is generally tied to Activity.onStart of the containing Activity's lifecycle.
onStop
@MainThread
public void onStop()
Called when the Fragment is no longer started. This is generally tied to Activity.onStop of the containing Activity's lifecycle.
onViewStateRestored
@MainThread
public void onViewStateRestored(@Nullable Bundle savedInstanceState)
Called when all saved state has been restored into the view hierarchy of the fragment. This can be used to do initialization based on saved state that you are letting the view hierarchy track itself, such as whether check box widgets are currently checked. This is called after onViewCreated and before onStart.
requireComponentDialog
public final @NonNull ComponentDialog requireComponentDialog()
Return the ComponentDialog this fragment is currently controlling.
| Throws | |
|---|---|
java.lang.IllegalStateException |
if the Dialog found is not a ComponentDialog or if Dialog has not yet been created (before |
| See also | |
|---|---|
requireDialog |
requireDialog
public final @NonNull Dialog requireDialog()
Return the Dialog this fragment is currently controlling.
| Throws | |
|---|---|
java.lang.IllegalStateException |
if the Dialog has not yet been created (before |
| See also | |
|---|---|
getDialog |
setCancelable
public void setCancelable(boolean cancelable)
Control whether the shown Dialog is cancelable. Use this instead of directly calling Dialog.setCancelable(boolean), because DialogFragment needs to change its behavior based on this.
| Parameters | |
|---|---|
boolean cancelable |
If true, the dialog is cancelable. The default is true. |
setShowsDialog
public void setShowsDialog(boolean showsDialog)
Controls whether this fragment should be shown in a dialog. If not set, no Dialog will be created and the fragment's view hierarchy will thus not be added to it. This allows you to instead use it as a normal fragment (embedded inside of its activity).
This is normally set for you based on whether the fragment is associated with a container view ID passed to FragmentTransaction.add(int, Fragment). If the fragment was added with a container, setShowsDialog will be initialized to false; otherwise, it will be true.
If calling this manually, it should be called in onCreate as calling it any later will have no effect.
| Parameters | |
|---|---|
boolean showsDialog |
If true, the fragment will be displayed in a Dialog. If false, no Dialog will be created and the fragment's view hierarchy left undisturbed. |
setStyle
public void setStyle(int style, @StyleRes int theme)
Call to customize the basic appearance and behavior of the fragment's dialog. This can be used for some common dialog behaviors, taking care of selecting flags, theme, and other options for you. The same effect can be achieve by manually setting Dialog and Window attributes yourself. Calling this after the fragment's Dialog is created will have no effect.
| Parameters | |
|---|---|
int style |
Selects a standard style: may be |
@StyleRes int theme |
Optional custom theme. If 0, an appropriate theme (based on the style) will be selected for you. |
show
public void show(@NonNull FragmentManager manager, @Nullable String tag)
Display the dialog, adding the fragment to the given FragmentManager. This is a convenience for explicitly creating a transaction, adding the fragment to it with the given tag, and committing it. This does not add the transaction to the fragment back stack. When the fragment is dismissed, a new transaction will be executed to remove it from the activity.
| Parameters | |
|---|---|
@NonNull FragmentManager manager |
The FragmentManager this fragment will be added to. |
@Nullable String tag |
The tag for this fragment, as per |
show
public int show(@NonNull FragmentTransaction transaction, @Nullable String tag)
Display the dialog, adding the fragment using an existing transaction and then committing the transaction.
| Parameters | |
|---|---|
@NonNull FragmentTransaction transaction |
An existing transaction in which to add the fragment. |
@Nullable String tag |
The tag for this fragment, as per |
| Returns | |
|---|---|
int |
Returns the identifier of the committed transaction, as per |
showNow
public void showNow(@NonNull FragmentManager manager, @Nullable String tag)
Display the dialog, immediately adding the fragment to the given FragmentManager. This is a convenience for explicitly creating a transaction, adding the fragment to it with the given tag, and calling commitNow. This does not add the transaction to the fragment back stack. When the fragment is dismissed, a new transaction will be executed to remove it from the activity.
| Parameters | |
|---|---|
@NonNull FragmentManager manager |
The FragmentManager this fragment will be added to. |
@Nullable String tag |
The tag for this fragment, as per |