DialogFragment


class DialogFragment : Fragment, 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

const Int

Style for setStyle: a basic, normal dialog.

const Int

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

const Int

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

const Int

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

Public constructors

Constructor used by the default FragmentFactory.

DialogFragment(contentLayoutId: @LayoutRes Int)

Alternate constructor that can be called from your default, no argument constructor to provide a default layout that will be inflated by onCreateView.

Public functions

Unit

Dismiss the fragment and its dialog.

Unit

Version of dismiss that uses FragmentTransaction.commitAllowingStateLoss().

Unit

Version of dismiss that uses commitNow.

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.

Unit
@MainThread
onActivityCreated(savedInstanceState: Bundle?)

This function 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.

Unit

Called when a fragment is first attached to its context.

Unit
Unit
@MainThread
onCreate(savedInstanceState: Bundle?)

Called to do initial creation of a fragment.

Dialog
@MainThread
onCreateDialog(savedInstanceState: Bundle?)

Override to build your own custom Dialog container.

Unit

Remove dialog.

Unit

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

Unit
LayoutInflater
onGetLayoutInflater(savedInstanceState: Bundle?)

Returns the LayoutInflater used to inflate Views of this Fragment.

Unit

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.

Unit

Called when the Fragment is visible to the user.

Unit

Called when the Fragment is no longer started.

Unit
@MainThread
onViewStateRestored(savedInstanceState: Bundle?)

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

ComponentDialog

Return the ComponentDialog this fragment is currently controlling.

Dialog

Return the Dialog this fragment is currently controlling.

Unit
setCancelable(cancelable: Boolean)

Control whether the shown Dialog is cancelable.

Unit
setShowsDialog(showsDialog: Boolean)

Controls whether this fragment should be shown in a dialog.

Unit
setStyle(style: Int, theme: @StyleRes Int)

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

Unit
show(manager: FragmentManager, tag: String?)

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

Int
show(transaction: FragmentTransaction, tag: String?)

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

Unit
showNow(manager: FragmentManager, tag: String?)

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

Inherited functions

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

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

From android.content.ComponentCallbacks
From androidx.fragment.app.Fragment
Unit
dump(
    prefix: String,
    fd: FileDescriptor?,
    writer: PrintWriter,
    args: Array<String!>?
)

Print the Fragments's state into the given stream.

Boolean
equals(o: Any?)

Subclasses can not override equals().

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.

Bundle?

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

FragmentManager

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

Context?

Return the Context this fragment is currently associated with.

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.

ViewModelProvider.Factory
Any?

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

Any?

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.

FragmentManager?

This function is deprecated.

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

Any?

Return the host object of this fragment.

Int

Return the identifier this fragment is known by.

LayoutInflater

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

Lifecycle

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

LoaderManager

This function is deprecated.

Use LoaderManager.getInstance(this).

Fragment?

Returns the parent Fragment containing this Fragment.

FragmentManager

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

Any?

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

Resources

Return requireActivity().getResources().

Boolean

This function is deprecated.

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

Any?

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.

SavedStateRegistry
Any?

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

Any?

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

String

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

String
getString(resId: @StringRes Int, formatArgs: Array<Any!>?)

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.

String?

Get the tag name of the fragment, if specified.

Fragment?

This function 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.

Int

This function 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.

CharSequence

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

Boolean

This function is deprecated.

Use setMaxLifecycle instead.

View?

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

LifecycleOwner

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

LiveData<LifecycleOwner!>

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

ViewModelStore

Returns the ViewModelStore associated with this Fragment

Int

Subclasses can not override hashCode().

java-static Fragment
instantiate(context: Context, fname: String)

This function is deprecated.

Use getFragmentFactory and instantiate

java-static Fragment
instantiate(context: Context, fname: String, args: Bundle?)

This function is deprecated.

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

Boolean

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

Boolean

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

Boolean

Return true if the fragment has been hidden.

Boolean

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

Boolean

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

Boolean

Return true if the fragment is in the resumed state.

Boolean

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

Boolean

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

Unit
onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)

This function 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.

Unit

This function is deprecated.

See onAttach.

Unit

This function is deprecated.

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

Unit
Boolean

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

Animation?
@MainThread
onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int)

Called when a fragment loads an animation.

Animator?
@MainThread
onCreateAnimator(transit: Int, enter: Boolean, nextAnim: Int)

Called when a fragment loads an animator.

Unit
@MainThread
onCreateContextMenu(
    menu: ContextMenu,
    v: View,
    menuInfo: ContextMenu.ContextMenuInfo?
)

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

Unit

This function 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.

View?
@MainThread
onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
)

Called to have the fragment instantiate its user interface view.

Unit

Called when the fragment is no longer in use.

Unit

This function 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.

Unit

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

Unit
@UiThread
@CallSuper
onInflate(
    activity: Activity,
    attrs: AttributeSet,
    savedInstanceState: Bundle?
)

This function is deprecated.

See onInflate.

Unit
@UiThread
@CallSuper
onInflate(
    context: Context,
    attrs: AttributeSet,
    savedInstanceState: Bundle?
)

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

Unit
Unit
onMultiWindowModeChanged(isInMultiWindowMode: Boolean)

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

Boolean

This function 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.

Unit

This function 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.

Unit

Called when the Fragment is no longer resumed.

Unit
onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean)

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

Unit

This function 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.

Unit
@MainThread
onPrimaryNavigationFragmentChanged(
    isPrimaryNavigationFragment: Boolean
)

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

Unit
onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String!>,
    grantResults: IntArray
)

This function 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.

Unit

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

Unit
@MainThread
onViewCreated(view: View, savedInstanceState: Bundle?)

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

Unit

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

Unit
postponeEnterTransition(duration: Long, timeUnit: TimeUnit)

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

ActivityResultLauncher<I!>
@MainThread
<I, O> registerForActivityResult(
    contract: ActivityResultContract<I!, O!>,
    callback: ActivityResultCallback<O!>
)

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

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

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

Unit

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

Unit
requestPermissions(permissions: Array<String!>, requestCode: Int)

This function 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.

FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

Bundle

Return the arguments supplied when the fragment was instantiated.

Context

Return the Context this fragment is currently associated with.

FragmentManager

This function 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.

Any

Return the host object of this fragment.

Fragment

Returns the parent Fragment containing this Fragment.

View

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

Unit

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

Unit

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

Unit

Supply the construction arguments for this fragment.

Unit

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.

Unit
setEnterTransition(transition: Any?)

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

Unit

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.

Unit
setExitTransition(transition: Any?)

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.

Unit

This function 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.

Unit

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

Unit
setMenuVisibility(menuVisible: Boolean)

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

Unit
setReenterTransition(transition: Any?)

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

Unit

This function is deprecated.

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

Unit
setReturnTransition(transition: Any?)

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.

Unit

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

Unit

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

Unit
setTargetFragment(fragment: Fragment?, requestCode: Int)

This function 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.

Unit
setUserVisibleHint(isVisibleToUser: Boolean)

This function 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.

Unit

Call startActivity from the fragment's containing Activity.

Unit
startActivity(intent: Intent, options: Bundle?)

Call startActivity from the fragment's containing Activity.

Unit
startActivityForResult(intent: Intent, requestCode: Int)

This function 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.

Unit
startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?)

This function 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.

Unit
startIntentSenderForResult(
    intent: IntentSender,
    requestCode: Int,
    fillInIntent: Intent?,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int,
    options: Bundle?
)

This function 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.

Unit

Begin postponed transitions after postponeEnterTransition was called.

String
Unit

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 Unit
onCreateContextMenu(
    p: ContextMenu!,
    p1: View!,
    p2: ContextMenu.ContextMenuInfo!
)
From androidx.lifecycle.ViewModelStoreOwner

Constants

STYLE_NORMAL

Added in 1.1.0
const val STYLE_NORMAL = 0: Int

Style for setStyle: a basic, normal dialog.

STYLE_NO_FRAME

Added in 1.1.0
const val STYLE_NO_FRAME = 2: Int

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
const val STYLE_NO_INPUT = 3: Int

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
const val STYLE_NO_TITLE = 1: Int

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

Public constructors

DialogFragment

Added in 1.1.0
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
DialogFragment(contentLayoutId: @LayoutRes Int)

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 functions

dismiss

Added in 1.1.0
fun dismiss(): Unit

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
fun dismissAllowingStateLoss(): Unit

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

dismissNow

Added in 1.5.0
@MainThread
fun dismissNow(): Unit

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

getDialog

Added in 1.1.0
fun getDialog(): Dialog?

Return the Dialog this fragment is currently controlling.

See also
requireDialog

getShowsDialog

Added in 1.1.0
fun getShowsDialog(): Boolean

Return the current value of setShowsDialog.

getTheme

Added in 1.1.0
fun getTheme(): @StyleRes Int

isCancelable

Added in 1.1.0
fun isCancelable(): Boolean

Return the current value of setCancelable.

onActivityCreated

@MainThread
fun onActivityCreated(savedInstanceState: Bundle?): Unit

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
fun onAttach(context: Context): Unit

Called when a fragment is first attached to its context. onCreate will be called after this.

onCancel

Added in 1.1.0
fun onCancel(dialog: DialogInterface): Unit

onCreate

@MainThread
fun onCreate(savedInstanceState: Bundle?): Unit

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
savedInstanceState: Bundle?

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

onCreateDialog

Added in 1.1.0
@MainThread
fun onCreateDialog(savedInstanceState: Bundle?): Dialog

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
savedInstanceState: Bundle?

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

Returns
Dialog

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

onDestroyView

@MainThread
fun onDestroyView(): Unit

Remove dialog.

onDetach

@MainThread
fun onDetach(): Unit

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

onDismiss

Added in 1.1.0
@CallSuper
fun onDismiss(dialog: DialogInterface): Unit

onGetLayoutInflater

fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater

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
fun onSaveInstanceState(outState: Bundle): Unit

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
outState: Bundle

Bundle in which to place your saved state.

onStart

@MainThread
fun onStart(): Unit

Called when the Fragment is visible to the user. This is generally tied to Activity.onStart of the containing Activity's lifecycle.

onStop

@MainThread
fun onStop(): Unit

Called when the Fragment is no longer started. This is generally tied to Activity.onStop of the containing Activity's lifecycle.

onViewStateRestored

@MainThread
fun onViewStateRestored(savedInstanceState: Bundle?): Unit

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
savedInstanceState: Bundle?

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

requireComponentDialog

Added in 1.6.0
fun requireComponentDialog(): ComponentDialog

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
fun requireDialog(): Dialog

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
fun setCancelable(cancelable: Boolean): Unit

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
cancelable: Boolean

If true, the dialog is cancelable. The default is true.

setShowsDialog

Added in 1.1.0
fun setShowsDialog(showsDialog: Boolean): Unit

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
showsDialog: Boolean

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
fun setStyle(style: Int, theme: @StyleRes Int): Unit

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
style: Int

Selects a standard style: may be STYLE_NORMAL, STYLE_NO_TITLE, STYLE_NO_FRAME, or STYLE_NO_INPUT.

theme: @StyleRes Int

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

show

Added in 1.1.0
fun show(manager: FragmentManager, tag: String?): Unit

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
manager: FragmentManager

The FragmentManager this fragment will be added to.

tag: String?

The tag for this fragment, as per FragmentTransaction.add.

show

Added in 1.1.0
fun show(transaction: FragmentTransaction, tag: String?): Int

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

Parameters
transaction: FragmentTransaction

An existing transaction in which to add the fragment.

tag: String?

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
fun showNow(manager: FragmentManager, tag: String?): Unit

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
manager: FragmentManager

The FragmentManager this fragment will be added to.

tag: String?

The tag for this fragment, as per FragmentTransaction.add.