DialogFragment


public class DialogFragment extends Fragment implements DialogInterface.OnCancelListener, DialogInterface.OnDismissListener

Known direct subclasses
AppCompatDialogFragment

A special version of DialogFragment which uses an AppCompatDialog in place of a platform-styled dialog.

MediaRouteChooserDialogFragment

Media route chooser dialog fragment.

MediaRouteControllerDialogFragment

Media route controller dialog fragment.

PreferenceDialogFragmentCompat

Abstract base class which presents a dialog associated with a DialogPreference.


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:

  1. Lifecycle
  2. Basic Dialog
  3. Alert Dialog
  4. Selecting Between Dialog or Embedding

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 for setStyle: a basic, normal dialog.

static final int

Style for setStyle: don't draw any frame at all; the view hierarchy returned by onCreateView is entirely responsible for drawing the dialog.

static final int

Style for setStyle: like STYLE_NO_FRAME, but also disables all input to the dialog.

static final int

Style for setStyle: don't include a title area.

Public constructors

Constructor used by the default FragmentFactory.

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.

Public methods

void

Dismiss the fragment and its dialog.

void

Version of dismiss that uses FragmentTransaction.commitAllowingStateLoss().

void

Version of dismiss that uses commitNow.

@Nullable Dialog

Return the Dialog this fragment is currently controlling.

boolean

Return the current value of setShowsDialog.

@StyleRes int
boolean

Return the current value of setCancelable.

void

This method is deprecated.

use onCreateDialog for code touching the dialog created by onCreateDialog, onViewCreated for code touching the view created by onCreateView and onCreate for other initialization.

void

Called when a fragment is first attached to its context.

void
void
@MainThread
onCreate(@Nullable Bundle savedInstanceState)

Called to do initial creation of a fragment.

@NonNull Dialog

Override to build your own custom Dialog container.

void

Remove dialog.

void

Called when the fragment is no longer attached to its activity.

void
@NonNull LayoutInflater
onGetLayoutInflater(@Nullable Bundle savedInstanceState)

Returns the LayoutInflater used to inflate Views of this Fragment.

void

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.

void

Called when the Fragment is visible to the user.

void

Called when the Fragment is no longer started.

void

Called when all saved state has been restored into the view hierarchy of the fragment.

final @NonNull ComponentDialog

Return the ComponentDialog this fragment is currently controlling.

final @NonNull Dialog

Return the Dialog this fragment is currently controlling.

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
setStyle(int style, @StyleRes int theme)

Call to customize the basic appearance and behavior of the fragment's dialog.

void

Display the dialog, adding the fragment to the given FragmentManager.

int

Display the dialog, adding the fragment using an existing transaction and then committing the transaction.

void

Display the dialog, immediately adding the fragment to the given FragmentManager.

Inherited methods

From androidx.activity.result.ActivityResultCaller
abstract ActivityResultLauncher<I>
<I, O> registerForActivityResult(
    ActivityResultContract<I, O> contract,
    ActivityResultCallback<O> callback
)

Register a request to start an activity for result, designated by the given contract.

From android.content.ComponentCallbacks
abstract void
abstract void
From androidx.fragment.app.Fragment
void
dump(
    @NonNull String prefix,
    @Nullable FileDescriptor fd,
    @NonNull PrintWriter writer,
    @Nullable String[] args
)

Print the Fragments's state into the given stream.

final boolean

Subclasses can not override equals().

final @Nullable FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

boolean

Returns whether the the exit transition and enter transition overlap or not.

boolean

Returns whether the the return transition and reenter transition overlap or not.

final @Nullable Bundle

Return the arguments supplied when the fragment was instantiated, if any.

final @NonNull FragmentManager

Return a private FragmentManager for placing and managing Fragments inside of this Fragment.

@Nullable Context

Return the Context this fragment is currently associated with.

@NonNull CreationExtras

The Fragment's arguments when this is first called will be used as the defaults to any androidx.lifecycle.SavedStateHandle passed to a view model created using this extra.

@NonNull ViewModelProvider.Factory
@Nullable Object

Returns the Transition that will be used to move Views into the initial scene.

@Nullable Object

Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

final @Nullable FragmentManager

This method is deprecated.

This has been removed in favor of getParentFragmentManager() which throws an IllegalStateException if the FragmentManager is null.

final @Nullable Object

Return the host object of this fragment.

final int

Return the identifier this fragment is known by.

final @NonNull LayoutInflater

Returns the cached LayoutInflater used to inflate Views of this Fragment.

@NonNull Lifecycle

Overriding this method is no longer supported and this method will be made final in a future version of Fragment.

@NonNull LoaderManager

This method is deprecated.

Use LoaderManager.getInstance(this).

final @Nullable Fragment

Returns the parent Fragment containing this Fragment.

final @NonNull FragmentManager

Return the FragmentManager for interacting with fragments associated with this fragment's activity.

@Nullable Object

Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

final @NonNull Resources

Return requireActivity().getResources().

final boolean

This method is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

@Nullable Object

Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

final @NonNull SavedStateRegistry
@Nullable Object

Returns the Transition that will be used for shared elements transferred into the content Scene.

@Nullable Object

Return the Transition that will be used for shared elements transferred back during a pop of the back stack.

final @NonNull String
getString(@StringRes int resId)

Return a localized string from the application's package's default string table.

final @NonNull String
getString(@StringRes int resId, @Nullable Object[] formatArgs)

Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in java.util.Formatter and format.

final @Nullable String

Get the tag name of the fragment, if specified.

final @Nullable Fragment

This method is deprecated.

Instead of using a target fragment to pass results, use setFragmentResult to deliver results to FragmentResultListener instances registered by other fragments via setFragmentResultListener.

final int

This method is deprecated.

When using the target fragment replacement of setFragmentResultListener and setFragmentResult, consider using setArguments to pass a requestKey if you need to support dynamic request keys.

final @NonNull CharSequence
getText(@StringRes int resId)

Return a localized, styled CharSequence from the application's package's default string table.

boolean

This method is deprecated.

Use setMaxLifecycle instead.

@Nullable View

Get the root view for the fragment's layout (the one returned by onCreateView), if provided.

@NonNull LifecycleOwner

Get a LifecycleOwner that represents the Fragment's View lifecycle.

@NonNull LiveData<LifecycleOwner>

Retrieve a LiveData which allows you to observe the lifecycle of the Fragment's View.

@NonNull ViewModelStore

Returns the ViewModelStore associated with this Fragment

final int

Subclasses can not override hashCode().

static @NonNull Fragment

This method is deprecated.

Use getFragmentFactory and instantiate

static @NonNull Fragment
instantiate(
    @NonNull Context context,
    @NonNull String fname,
    @Nullable Bundle args
)

This method is deprecated.

Use getFragmentFactory and instantiate, manually calling setArguments on the returned Fragment.

final boolean

Return true if the fragment is currently added to its activity.

final boolean

Return true if the fragment has been explicitly detached from the UI.

final boolean

Return true if the fragment has been hidden.

final boolean

Return true if the layout is included as part of an activity view hierarchy via the tag.

final boolean

Return true if this fragment is currently being removed from its activity.

final boolean

Return true if the fragment is in the resumed state.

final boolean

Returns true if this fragment is added and its state has already been saved by its host.

final boolean

Return true if the fragment is currently visible to the user.

void
onActivityResult(int requestCode, int resultCode, @Nullable Intent data)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void

This method is deprecated.

See onAttach.

void

This method is deprecated.

The responsibility for listening for fragments being attached has been moved to FragmentManager.

void
boolean

This hook is called whenever an item in a context menu is selected.

@Nullable Animation
@MainThread
onCreateAnimation(int transit, boolean enter, int nextAnim)

Called when a fragment loads an animation.

@Nullable Animator
@MainThread
onCreateAnimator(int transit, boolean enter, int nextAnim)

Called when a fragment loads an animator.

void

Called when a context menu for the view is about to be shown.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

@Nullable View
@MainThread
onCreateView(
    @NonNull LayoutInflater inflater,
    @Nullable ViewGroup container,
    @Nullable Bundle savedInstanceState
)

Called to have the fragment instantiate its user interface view.

void

Called when the fragment is no longer in use.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void
@MainThread
onHiddenChanged(boolean hidden)

Called when the hidden state (as returned by isHidden of the fragment or another fragment in its hierarchy has changed.

void
@UiThread
@CallSuper
onInflate(
    @NonNull Activity activity,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

This method is deprecated.

See onInflate.

void
@UiThread
@CallSuper
onInflate(
    @NonNull Context context,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.

void
void
onMultiWindowModeChanged(boolean isInMultiWindowMode)

Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa.

boolean

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void

Called when the Fragment is no longer resumed.

void
onPictureInPictureModeChanged(boolean isInPictureInPictureMode)

Called by the system when the activity changes to and from picture-in-picture mode.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void
@MainThread
onPrimaryNavigationFragmentChanged(
    boolean isPrimaryNavigationFragment
)

Callback for when the primary navigation state of this Fragment has changed.

void
onRequestPermissionsResult(
    int requestCode,
    @NonNull String[] permissions,
    @NonNull int[] grantResults
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void

Called when the fragment is visible to the user and actively running.

void
@MainThread
onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)

Called immediately after onCreateView has returned, but before any saved state has been restored in to the view.

void

Postpone the entering Fragment transition until startPostponedEnterTransition or executePendingTransactions has been called.

final void
postponeEnterTransition(long duration, @NonNull TimeUnit timeUnit)

Postpone the entering Fragment transition for a given amount of time and then call startPostponedEnterTransition.

final @NonNull ActivityResultLauncher<I>
@MainThread
<I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultCallback<O> callback
)

Register a request to start an activity for result, designated by the given contract.

final @NonNull ActivityResultLauncher<I>
@MainThread
<I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultRegistry registry,
    @NonNull ActivityResultCallback<O> callback
)

Register a request to start an activity for result, designated by the given contract.

void

Registers a context menu to be shown for the given view (multiple views can show the context menu).

final void
requestPermissions(@NonNull String[] permissions, int requestCode)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

final @NonNull FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

final @NonNull Bundle

Return the arguments supplied when the fragment was instantiated.

final @NonNull Context

Return the Context this fragment is currently associated with.

final @NonNull FragmentManager

This method is deprecated.

This has been renamed to getParentFragmentManager() to make it clear that you are accessing the FragmentManager that contains this Fragment and not the FragmentManager associated with child Fragments.

final @NonNull Object

Return the host object of this fragment.

final @NonNull Fragment

Returns the parent Fragment containing this Fragment.

final @NonNull View

Get the root view for the fragment's layout (the one returned by onCreateView).

void

Sets whether the the exit transition and enter transition overlap or not.

void

Sets whether the the return transition and reenter transition overlap or not.

void

Supply the construction arguments for this fragment.

void

When custom transitions are used with Fragments, the enter transition callback is called when this Fragment is attached or detached when not popping the back stack.

void

Sets the Transition that will be used to move Views into the initial scene.

void

When custom transitions are used with Fragments, the exit transition callback is called when this Fragment is attached or detached when popping the back stack.

void

Sets the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

void
setHasOptionsMenu(boolean hasMenu)

This method is deprecated.

This method is no longer needed when using a MenuProvider to provide a Menu to your activity, which replaces onCreateOptionsMenu as the recommended way to provide a consistent, optionally Lifecycle-aware, and modular way to handle menu creation and item selection.

void

Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.saveFragmentInstanceState.

void
setMenuVisibility(boolean menuVisible)

Set a hint for whether this fragment's menu should be visible.

void

Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

void
setRetainInstance(boolean retain)

This method is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

void

Sets the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

void

Sets the Transition that will be used for shared elements transferred into the content Scene.

void

Sets the Transition that will be used for shared elements transferred back during a pop of the back stack.

void
setTargetFragment(@Nullable Fragment fragment, int requestCode)

This method is deprecated.

Instead of using a target fragment to pass results, the fragment requesting a result should use setFragmentResultListener to register a FragmentResultListener with a requestKey using its parent fragment manager.

void
setUserVisibleHint(boolean isVisibleToUser)

This method is deprecated.

If you are manually calling this method, use setMaxLifecycle instead.

boolean

Gets whether you should show UI with rationale before requesting a permission.

void

Call startActivity from the fragment's containing Activity.

void

Call startActivity from the fragment's containing Activity.

void
startActivityForResult(@NonNull Intent intent, int requestCode)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void
startActivityForResult(
    @NonNull Intent intent,
    int requestCode,
    @Nullable Bundle options
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void
startIntentSenderForResult(
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags,
    @Nullable Bundle options
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void

Begin postponed transitions after postponeEnterTransition was called.

@NonNull String
void

Prevents a context menu to be shown for the given view.

From androidx.lifecycle.HasDefaultViewModelProviderFactory
From androidx.lifecycle.LifecycleOwner
abstract Lifecycle
From androidx.savedstate.SavedStateRegistryOwner
From android.view.View.OnCreateContextMenuListener
abstract void
From androidx.lifecycle.ViewModelStoreOwner

Constants

STYLE_NORMAL

Added in 1.1.0
public static final int STYLE_NORMAL = 0

Style for setStyle: a basic, normal dialog.

STYLE_NO_FRAME

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
public static final int STYLE_NO_TITLE = 1

Style for setStyle: don't include a title area.

Public constructors

DialogFragment

Added in 1.1.0
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

Added in 1.3.0
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);
  }
}
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.

Public methods

dismiss

Added in 1.1.0
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

Added in 1.1.0
public void dismissAllowingStateLoss()

Version of dismiss that uses FragmentTransaction.commitAllowingStateLoss(). See linked documentation for further details.

dismissNow

Added in 1.5.0
@MainThread
public void dismissNow()

Version of dismiss that uses commitNow. See linked documentation for further details.

getDialog

Added in 1.1.0
public @Nullable Dialog getDialog()

Return the Dialog this fragment is currently controlling.

See also
requireDialog

getShowsDialog

Added in 1.1.0
public boolean getShowsDialog()

Return the current value of setShowsDialog.

getTheme

Added in 1.1.0
public @StyleRes int getTheme()

isCancelable

Added in 1.1.0
public boolean isCancelable()

Return the current value of setCancelable.

onActivityCreated

@MainThread
public void onActivityCreated(@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.

onCancel

Added in 1.1.0
public void onCancel(@NonNull DialogInterface dialog)

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.

Parameters
@Nullable Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

onCreateDialog

Added in 1.1.0
@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.

Parameters
@Nullable Bundle savedInstanceState

The last saved instance state of the Fragment, or null if this is a freshly created Fragment.

Returns
@NonNull Dialog

Return a new Dialog instance to be displayed by the Fragment.

onDestroyView

@MainThread
public void onDestroyView()

Remove dialog.

onDetach

@MainThread
public void onDetach()

Called when the fragment is no longer attached to its activity. This is called after onDestroy.

onDismiss

Added in 1.1.0
@CallSuper
public void onDismiss(@NonNull DialogInterface dialog)

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.

Parameters
@NonNull Bundle outState

Bundle in which to place your saved 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.

Parameters
@Nullable Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

requireComponentDialog

Added in 1.6.0
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 onCreateDialog) or has been destroyed (after onDestroyView.

See also
requireDialog

requireDialog

Added in 1.1.0
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 onCreateDialog) or has been destroyed (after onDestroyView.

See also
getDialog

setCancelable

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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 STYLE_NORMAL, STYLE_NO_TITLE, STYLE_NO_FRAME, or STYLE_NO_INPUT.

@StyleRes int theme

Optional custom theme. If 0, an appropriate theme (based on the style) will be selected for you.

show

Added in 1.1.0
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 FragmentTransaction.add.

show

Added in 1.1.0
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 FragmentTransaction.add.

Returns
int

Returns the identifier of the committed transaction, as per FragmentTransaction.commit().

showNow

Added in 1.1.0
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 FragmentTransaction.add.