How to Get a Dialog Box to Show Again

A dialog is a minor window that prompts the user to make a decision or enter additional information. A dialog does not make full the screen and is normally used for modal events that require users to have an action earlier they can proceed.

Dialog Design

For information nearly how to design your dialogs, including recommendations for language, read the Dialogs design guide.

The Dialog class is the base course for dialogs, but you should avoid instantiating Dialog directly. Instead, employ ane of the post-obit subclasses:

AlertDialog
A dialog that can show a title, up to iii buttons, a list of selectable items, or a custom layout.
DatePickerDialog or TimePickerDialog
A dialog with a pre-divers UI that allows the user to select a date or time.

Caution: Android includes another dialog course called ProgressDialog that shows a dialog with a progress bar. This widget is deprecated because it prevents users from interacting with the app while progress is being displayed. If you need to indicate loading or indeterminate progress, yous should follow the design guidelines for Progress & Activity and employ a ProgressBar in your layout, instead of using ProgressDialog.

These classes define the style and structure for your dialog, but you should apply a DialogFragment as a container for your dialog. The DialogFragment class provides all the controls you need to create your dialog and manage its appearance, instead of calling methods on the Dialog object.

Using DialogFragment to manage the dialog ensures that it correctly handles lifecycle events such as when the user presses the Dorsum push button or rotates the screen. The DialogFragment class likewise allows you to reuse the dialog's UI as an embeddable component in a larger UI, just like a traditional Fragment (such as when you want the dialog UI to announced differently on large and small screens).

The following sections in this guide describe how to use a DialogFragment in combination with an AlertDialog object. If you'd like to create a engagement or time picker, you should instead read the Pickers guide.

Notation: Considering the DialogFragment form was originally added with Android three.0 (API level 11), this document describes how to utilize the DialogFragment class that'south provided with the Support Library. By adding this library to your app, you can use DialogFragment and a variety of other APIs on devices running Android one.6 or higher. If the minimum version your app supports is API level eleven or college, then you tin use the framework version of DialogFragment, but exist enlightened that the links in this document are for the support library APIs. When using the support library, exist certain that you import android.support.v4.app.DialogFragment class and not android.app.DialogFragment.

Creating a Dialog Fragment

Y'all can attain a broad variety of dialog designs—including custom layouts and those described in the Dialogs design guide—past extending DialogFragment and creating an AlertDialog in the onCreateDialog() callback method.

For case, here'south a basic AlertDialog that's managed within a DialogFragment:

Kotlin

form StartGameDialogFragment : DialogFragment() {      override fun onCreateDialog(savedInstanceState: Bundle): Dialog {         return activity?.let {             // Use the Builder form for convenient dialog construction             val builder = AlertDialog.Architect(it)             builder.setMessage(R.string.dialog_start_game)                     .setPositiveButton(R.string.showtime,                             DialogInterface.OnClickListener { dialog, id ->                                 // START THE GAME!                             })                     .setNegativeButton(R.cord.cancel,                             DialogInterface.OnClickListener { dialog, id ->                                 // User cancelled the dialog                             })             // Create the AlertDialog object and render information technology             builder.create()         } ?: throw IllegalStateException("Action cannot be null")     } }            

Coffee

public class StartGameDialogFragment extends DialogFragment {     @Override     public Dialog onCreateDialog(Package savedInstanceState) {         // Apply the Architect form for convenient dialog construction         AlertDialog.Builder builder = new AlertDialog.Architect(getActivity());         builder.setMessage(R.cord.dialog_start_game)                .setPositiveButton(R.string.offset, new DialogInterface.OnClickListener() {                    public void onClick(DialogInterface dialog, int id) {                        // START THE GAME!                    }                })                .setNegativeButton(R.cord.cancel, new DialogInterface.OnClickListener() {                    public void onClick(DialogInterface dialog, int id) {                        // User cancelled the dialog                    }                });         // Create the AlertDialog object and return it         render builder.create();     } }            

Effigy 1. A dialog with a message and 2 activity buttons.

Now, when you create an instance of this class and call bear witness() on that object, the dialog appears every bit shown in figure ane.

The side by side department describes more than almost using the AlertDialog.Architect APIs to create the dialog.

Depending on how complex your dialog is, you lot can implement a diversity of other callback methods in the DialogFragment, including all the basic fragment lifecycle methods.

Building an Alert Dialog

The AlertDialog class allows you lot to build a variety of dialog designs and is often the simply dialog class yous'll need. Every bit shown in figure 2, there are three regions of an alert dialog:

Figure 2. The layout of a dialog.

  1. Title

    This is optional and should be used only when the content area is occupied by a detailed message, a list, or custom layout. If you lot demand to country a simple message or question (such every bit the dialog in effigy 1), you don't need a title.

  2. Content area

    This can display a bulletin, a list, or other custom layout.

  3. Action buttons

    There should be no more three action buttons in a dialog.

The AlertDialog.Builder class provides APIs that allow you to create an AlertDialog with these kinds of content, including a custom layout.

To build an AlertDialog:

Kotlin

// 1. Instantiate an <code><a href="/reference/android/app/AlertDialog.Builder.html">AlertDialog.Builder</a></code> with its constructor val builder: AlertDialog.Architect? = activity?.permit {     AlertDialog.Builder(information technology) }  // 2. Chain together various setter methods to set the dialog characteristics architect?.setMessage(R.cord.dialog_message)         .setTitle(R.string.dialog_title)  // 3. Get the <code><a href="/reference/android/app/AlertDialog.html">AlertDialog</a></code> from <code><a href="/reference/android/app/AlertDialog.Builder.html#create()">create()</a></code> val dialog: AlertDialog? = builder?.create()            

Coffee

// 1. Instantiate an <code><a href="/reference/android/app/AlertDialog.Builder.html">AlertDialog.Builder</a></lawmaking> with its constructor AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  // 2. Chain together various setter methods to fix the dialog characteristics builder.setMessage(R.cord.dialog_message)        .setTitle(R.string.dialog_title);  // iii. Get the <code><a href="/reference/android/app/AlertDialog.html">AlertDialog</a></code> from <code><a href="/reference/android/app/AlertDialog.Builder.html#create()">create()</a></code> AlertDialog dialog = builder.create();            

The following topics bear witness how to define various dialog attributes using the AlertDialog.Architect grade.

Adding buttons

To add action buttons like those in figure two, call the setPositiveButton() and setNegativeButton() methods:

Kotlin

val alertDialog: AlertDialog? = activity?.let {     val builder = AlertDialog.Builder(it)     builder.apply {         setPositiveButton(R.string.ok,                 DialogInterface.OnClickListener { dialog, id ->                     // User clicked OK button                 })         setNegativeButton(R.cord.cancel,                 DialogInterface.OnClickListener { dialog, id ->                     // User cancelled the dialog                 })     }     // Set other dialog properties     ...      // Create the AlertDialog     builder.create() }            

Java

AlertDialog.Builder architect = new AlertDialog.Builder(getActivity()); // Add the buttons builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {            public void onClick(DialogInterface dialog, int id) {                // User clicked OK push button            }        }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {            public void onClick(DialogInterface dialog, int id) {                // User cancelled the dialog            }        }); // Set up other dialog properties ...  // Create the AlertDialog AlertDialog dialog = builder.create();            

The prepare...Push button() methods require a title for the button (supplied past a string resource) and a DialogInterface.OnClickListener that defines the action to take when the user presses the button.

At that place are three different action buttons you can add:

Positive
You should utilise this to accept and go along with the action (the "OK" activity).
Negative
You should use this to cancel the action.
Neutral
Y'all should use this when the user may not want to proceed with the action, just doesn't necessarily want to cancel. It appears betwixt the positive and negative buttons. For example, the activeness might be "Remind me later."

You can add together but ane of each button type to an AlertDialog. That is, you cannot have more than than ane "positive" button.

Figure 3. A dialog with a title and list.

Adding a list

There are three kinds of lists bachelor with the AlertDialog APIs:

  • A traditional single-choice listing
  • A persistent single-choice list (radio buttons)
  • A persistent multiple-choice list (checkboxes)

To create a single-choice list similar the i in figure 3, utilise the setItems() method:

Kotlin

override fun onCreateDialog(savedInstanceState: Package?): Dialog {     return activity?.allow {         val builder = AlertDialog.Builder(it)         builder.setTitle(R.string.pick_color)                 .setItems(R.assortment.colors_array,                         DialogInterface.OnClickListener { dialog, which ->                             // The 'which' argument contains the index position                             // of the selected item                         })         builder.create()     } ?: throw IllegalStateException("Activity cannot be nix") }            

Java

@Override public Dialog onCreateDialog(Bundle savedInstanceState) {     AlertDialog.Builder builder = new AlertDialog.Architect(getActivity());     architect.setTitle(R.string.pick_color)            .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {                public void onClick(DialogInterface dialog, int which) {                // The 'which' argument contains the index position                // of the selected item            }     });     return builder.create(); }            

Because the listing appears in the dialog's content area, the dialog cannot show both a message and a list and yous should ready a title for the dialog with setTitle(). To specify the items for the listing, phone call setItems(), passing an array. Alternatively, you can specify a list using setAdapter(). This allows you to back the listing with dynamic data (such as from a database) using a ListAdapter.

If you choose to back your list with a ListAdapter, always use a Loader so that the content loads asynchronously. This is described further in Building Layouts with an Adapter and the Loaders guide.

Note: Past default, touching a listing detail dismisses the dialog, unless you're using one of the following persistent choice lists.

Adding a persistent multiple-choice or single-selection list

To add a list of multiple-choice items (checkboxes) or unmarried-choice items (radio buttons), use the setMultiChoiceItems() or setSingleChoiceItems() methods, respectively.

Effigy 4. A listing of multiple-option items.

For instance, hither's how yous tin can create a multiple-choice list like the one shown in figure 4 that saves the selected items in an ArrayList:

Kotlin

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {     return activity?.let {         val selectedItems = ArrayList<Int>() // Where we track the selected items         val builder = AlertDialog.Builder(information technology)         // Set the dialog title         builder.setTitle(R.string.pick_toppings)                 // Specify the list array, the items to exist selected by default (aught for none),                 // and the listener through which to receive callbacks when items are selected                 .setMultiChoiceItems(R.array.toppings, zero,                         DialogInterface.OnMultiChoiceClickListener { dialog, which, isChecked ->                             if (isChecked) {                                 // If the user checked the particular, add it to the selected items                                 selectedItems.add together(which)                             } else if (selectedItems.contains(which)) {                                 // Else, if the item is already in the assortment, remove it                                 selectedItems.remove(which)                             }                         })                 // Set the activeness buttons                 .setPositiveButton(R.string.ok,                         DialogInterface.OnClickListener { dialog, id ->                             // User clicked OK, so save the selectedItems results somewhere                             // or return them to the component that opened the dialog                             ...                         })                 .setNegativeButton(R.string.cancel,                         DialogInterface.OnClickListener { dialog, id ->                             ...                         })          architect.create()     } ?: throw IllegalStateException("Action cannot be null") }            

Java

@Override public Dialog onCreateDialog(Bundle savedInstanceState) {     selectedItems = new ArrayList();  // Where we rails the selected items     AlertDialog.Builder builder = new AlertDialog.Architect(getActivity());     // Set the dialog title     architect.setTitle(R.string.pick_toppings)     // Specify the list assortment, the items to be selected by default (null for none),     // and the listener through which to receive callbacks when items are selected            .setMultiChoiceItems(R.array.toppings, null,                       new DialogInterface.OnMultiChoiceClickListener() {                @Override                public void onClick(DialogInterface dialog, int which,                        boolean isChecked) {                    if (isChecked) {                        // If the user checked the detail, add it to the selected items                        selectedItems.add together(which);                    } else if (selectedItems.contains(which)) {                        // Else, if the item is already in the array, remove it                        selectedItems.remove(which);                    }                }            })     // Fix the activity buttons            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {                @Override                public void onClick(DialogInterface dialog, int id) {                    // User clicked OK, so save the selectedItems results somewhere                    // or return them to the component that opened the dialog                    ...                }            })            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {                @Override                public void onClick(DialogInterface dialog, int id) {                    ...                }            });      render architect.create(); }            

Although both a traditional list and a list with radio buttons provide a "unmarried option" action, y'all should employ setSingleChoiceItems() if you want to persist the user's option. That is, if opening the dialog once again later should indicate what the user's current option is, then you create a listing with radio buttons.

Creating a Custom Layout

Figure v. A custom dialog layout.

If you want a custom layout in a dialog, create a layout and add it to an AlertDialog by calling setView() on your AlertDialog.Builder object.

By default, the custom layout fills the dialog window, but you tin withal use AlertDialog.Builder methods to add together buttons and a championship.

For example, here's the layout file for the dialog in Effigy five:

res/layout/dialog_signin.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="vertical"     android:layout_width="wrap_content"     android:layout_height="wrap_content">     <ImageView         android:src="@drawable/header_logo"         android:layout_width="match_parent"         android:layout_height="64dp"         android:scaleType="eye"         android:background="#FFFFBB33"         android:contentDescription="@string/app_name" />     <EditText         android:id="@+id/username"         android:inputType="textEmailAddress"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginTop="16dp"         android:layout_marginLeft="4dp"         android:layout_marginRight="4dp"         android:layout_marginBottom="4dp"         android:hint="@string/username" />     <EditText         android:id="@+id/password"         android:inputType="textPassword"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginTop="4dp"         android:layout_marginLeft="4dp"         android:layout_marginRight="4dp"         android:layout_marginBottom="16dp"         android:fontFamily="sans-serif"         android:hint="@cord/password"/> </LinearLayout>        

Tip: By default, when you lot set an EditText element to use the "textPassword" input type, the font family is set to monospace, so y'all should alter its font family to "sans-serif" so that both text fields use a matching font style.

To inflate the layout in your DialogFragment, get a LayoutInflater with getLayoutInflater() and call inflate(), where the first parameter is the layout resource ID and the second parameter is a parent view for the layout. You can then telephone call setView() to place the layout in the dialog.

Kotlin

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {     return activity?.let {         val builder = AlertDialog.Architect(it)         // Get the layout inflater         val inflater = requireActivity().layoutInflater;          // Inflate and set the layout for the dialog         // Laissez passer cypher as the parent view because its going in the dialog layout         builder.setView(inflater.inflate(R.layout.dialog_signin, null))                 // Add action buttons                 .setPositiveButton(R.string.signin,                         DialogInterface.OnClickListener { dialog, id ->                             // sign in the user ...                         })                 .setNegativeButton(R.string.cancel,                         DialogInterface.OnClickListener { dialog, id ->                             getDialog().cancel()                         })         architect.create()     } ?: throw IllegalStateException("Activity cannot exist cipher") }            

Java

@Override public Dialog onCreateDialog(Bundle savedInstanceState) {     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());     // Become the layout inflater     LayoutInflater inflater = requireActivity().getLayoutInflater();      // Inflate and set the layout for the dialog     // Laissez passer zip as the parent view because its going in the dialog layout     architect.setView(inflater.inflate(R.layout.dialog_signin, null))     // Add action buttons            .setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {                @Override                public void onClick(DialogInterface dialog, int id) {                    // sign in the user ...                }            })            .setNegativeButton(R.cord.cancel, new DialogInterface.OnClickListener() {                public void onClick(DialogInterface dialog, int id) {                    LoginDialogFragment.this.getDialog().cancel();                }            });     render builder.create(); }            

Tip: If you want a custom dialog, you tin can instead display an Action every bit a dialog instead of using the Dialog APIs. But create an activeness and set up its theme to Theme.Holo.Dialog in the <activity> manifest element:

<activity android:theme="@android:manner/Theme.Holo.Dialog" >          

That's information technology. The activity now displays in a dialog window instead of fullscreen.

Passing Events Back to the Dialog's Host

When the user touches one of the dialog's action buttons or selects an particular from its list, your DialogFragment might perform the necessary action itself, merely often you'll want to deliver the effect to the activity or fragment that opened the dialog. To do this, define an interface with a method for each type of click event. Then implement that interface in the host component that will receive the action events from the dialog.

For case, here'south a DialogFragment that defines an interface through which information technology delivers the events back to the host activity:

Kotlin

class NoticeDialogFragment : DialogFragment() {     // Use this instance of the interface to deliver action events     internal lateinit var listener: NoticeDialogListener      /* The activity that creates an instance of this dialog fragment must      * implement this interface in social club to receive event callbacks.      * Each method passes the DialogFragment in instance the host needs to query it. */     interface NoticeDialogListener {         fun onDialogPositiveClick(dialog: DialogFragment)         fun onDialogNegativeClick(dialog: DialogFragment)     }      // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener     override fun onAttach(context: Context) {         super.onAttach(context)         // Verify that the host activity implements the callback interface         try {             // Instantiate the NoticeDialogListener so we can send events to the host             listener = context every bit NoticeDialogListener         } catch (east: ClassCastException) {             // The activeness doesn't implement the interface, throw exception             throw ClassCastException((context.toString() +                     " must implement NoticeDialogListener"))         }     } }            

Java

public course NoticeDialogFragment extends DialogFragment {      /* The activity that creates an case of this dialog fragment must      * implement this interface in order to receive consequence callbacks.      * Each method passes the DialogFragment in case the host needs to query information technology. */     public interface NoticeDialogListener {         public void onDialogPositiveClick(DialogFragment dialog);         public void onDialogNegativeClick(DialogFragment dialog);     }      // Use this example of the interface to deliver activeness events     NoticeDialogListener listener;      // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener     @Override     public void onAttach(Context context) {         super.onAttach(context);         // Verify that the host activity implements the callback interface         attempt {             // Instantiate the NoticeDialogListener so nosotros can ship events to the host             listener = (NoticeDialogListener) context;         } catch (ClassCastException eastward) {             // The activity doesn't implement the interface, throw exception             throw new ClassCastException(action.toString()                     + " must implement NoticeDialogListener");         }     }     ... }            

The activity hosting the dialog creates an instance of the dialog with the dialog fragment'southward constructor and receives the dialog's events through an implementation of the NoticeDialogListener interface:

Kotlin

class MainActivity : FragmentActivity(),         NoticeDialogFragment.NoticeDialogListener {      fun showNoticeDialog() {         // Create an instance of the dialog fragment and testify information technology         val dialog = NoticeDialogFragment()         dialog.show(supportFragmentManager, "NoticeDialogFragment")     }      // The dialog fragment receives a reference to this Activity through the     // Fragment.onAttach() callback, which information technology uses to call the following methods     // defined by the NoticeDialogFragment.NoticeDialogListener interface     override fun onDialogPositiveClick(dialog: DialogFragment) {         // User touched the dialog's positive button     }      override fun onDialogNegativeClick(dialog: DialogFragment) {         // User touched the dialog's negative button     } }            

Java

public form MainActivity extends FragmentActivity                           implements NoticeDialogFragment.NoticeDialogListener{     ...      public void showNoticeDialog() {         // Create an case of the dialog fragment and testify it         DialogFragment dialog = new NoticeDialogFragment();         dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");     }      // The dialog fragment receives a reference to this Activity through the     // Fragment.onAttach() callback, which it uses to call the post-obit methods     // divers by the NoticeDialogFragment.NoticeDialogListener interface     @Override     public void onDialogPositiveClick(DialogFragment dialog) {         // User touched the dialog'due south positive button         ...     }      @Override     public void onDialogNegativeClick(DialogFragment dialog) {         // User touched the dialog's negative button         ...     } }            

Because the host activity implements the NoticeDialogListener—which is enforced by the onAttach() callback method shown above—the dialog fragment can use the interface callback methods to deliver click events to the activity:

Kotlin

              override fun onCreateDialog(savedInstanceState: Bundle): Dialog {         return activity?.allow {             // Build the dialog and gear up the push button click handlers             val builder = AlertDialog.Builder(information technology)              builder.setMessage(R.string.dialog_start_game)                     .setPositiveButton(R.string.start,                             DialogInterface.OnClickListener { dialog, id ->                                 // Send the positive button event dorsum to the host activity                                 listener.onDialogPositiveClick(this)                             })                     .setNegativeButton(R.string.abolish,                             DialogInterface.OnClickListener { dialog, id ->                                 // Send the negative push effect back to the host activity                                 listener.onDialogNegativeClick(this)                             })              builder.create()         } ?: throw IllegalStateException("Activity cannot exist null")     }            

Java

public form NoticeDialogFragment extends DialogFragment {     ...      @Override     public Dialog onCreateDialog(Bundle savedInstanceState) {         // Build the dialog and fix the button click handlers         AlertDialog.Builder architect = new AlertDialog.Architect(getActivity());         builder.setMessage(R.string.dialog_start_game)                .setPositiveButton(R.cord.beginning, new DialogInterface.OnClickListener() {                    public void onClick(DialogInterface dialog, int id) {                        // Send the positive push effect back to the host activity                        listener.onDialogPositiveClick(NoticeDialogFragment.this);                    }                })                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {                    public void onClick(DialogInterface dialog, int id) {                        // Ship the negative button event dorsum to the host activity                        listener.onDialogNegativeClick(NoticeDialogFragment.this);                    }                });         render builder.create();     } }            

Showing a Dialog

When you want to bear witness your dialog, create an instance of your DialogFragment and call bear witness(), passing the FragmentManager and a tag name for the dialog fragment.

Y'all can get the FragmentManager by calling getSupportFragmentManager() from the FragmentActivity or getFragmentManager() from a Fragment. For example:

Kotlin

fun confirmStartGame() {     val newFragment = StartGameDialogFragment()     newFragment.bear witness(supportFragmentManager, "game") }            

Java

public void confirmStartGame() {     DialogFragment newFragment = new StartGameDialogFragment();     newFragment.show(getSupportFragmentManager(), "game"); }            

The second statement, "game", is a unique tag name that the system uses to save and restore the fragment state when necessary. The tag also allows you to get a handle to the fragment by calling findFragmentByTag().

Showing a Dialog Fullscreen or equally an Embedded Fragment

Yous might have a UI blueprint in which yous want a piece of the UI to appear as a dialog in some situations, but as a total screen or embedded fragment in others (perchance depending on whether the device is a big screen or small screen). The DialogFragment class offers you this flexibility because information technology tin can still behave as an embeddable Fragment.

Notwithstanding, y'all cannot utilize AlertDialog.Builder or other Dialog objects to build the dialog in this example. If you lot desire the DialogFragment to be embeddable, you must define the dialog'due south UI in a layout, then load the layout in the onCreateView() callback.

Here's an example DialogFragment that tin appear as either a dialog or an embeddable fragment (using a layout named purchase_items.xml):

Kotlin

form CustomDialogFragment : DialogFragment() {      /** The organisation calls this to get the DialogFragment's layout, regardless     of whether it's existence displayed as a dialog or an embedded fragment. */     override fun onCreateView(             inflater: LayoutInflater,             container: ViewGroup?,             savedInstanceState: Bundle?     ): View {         // Inflate the layout to use every bit dialog or embedded fragment         return inflater.inflate(R.layout.purchase_items, container, faux)     }      /** The organization calls this only when creating the layout in a dialog. */     override fun onCreateDialog(savedInstanceState: Bundle): Dialog {         // The only reason yous might override this method when using onCreateView() is         // to modify whatsoever dialog characteristics. For example, the dialog includes a         // title by default, but your custom layout might not need information technology. So here you tin         // remove the dialog title, but you lot must call the superclass to become the Dialog.         val dialog = super.onCreateDialog(savedInstanceState)         dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)         render dialog     } }            

Java

public form CustomDialogFragment extends DialogFragment {     /** The system calls this to get the DialogFragment'south layout, regardless         of whether information technology'southward existence displayed as a dialog or an embedded fragment. */     @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,             Package savedInstanceState) {         // Inflate the layout to use as dialog or embedded fragment         return inflater.inflate(R.layout.purchase_items, container, false);     }      /** The system calls this just when creating the layout in a dialog. */     @Override     public Dialog onCreateDialog(Bundle savedInstanceState) {         // The simply reason you might override this method when using onCreateView() is         // to change whatever dialog characteristics. For example, the dialog includes a         // title by default, but your custom layout might not need it. So hither you lot tin can         // remove the dialog title, just you must call the superclass to go the Dialog.         Dialog dialog = super.onCreateDialog(savedInstanceState);         dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);         render dialog;     } }            

And here's some lawmaking that decides whether to evidence the fragment equally a dialog or a fullscreen UI, based on the screen size:

Kotlin

fun showDialog() {     val fragmentManager = supportFragmentManager     val newFragment = CustomDialogFragment()     if (isLargeLayout) {         // The device is using a large layout, then show the fragment as a dialog         newFragment.show(fragmentManager, "dialog")     } else {         // The device is smaller, and so bear witness the fragment fullscreen         val transaction = fragmentManager.beginTransaction()         // For a little polish, specify a transition animation         transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)         // To make information technology fullscreen, use the 'content' root view as the container         // for the fragment, which is ever the root view for the activity         transaction                 .add(android.R.id.content, newFragment)                 .addToBackStack(null)                 .commit()     } }            

Java

public void showDialog() {     FragmentManager fragmentManager = getSupportFragmentManager();     CustomDialogFragment newFragment = new CustomDialogFragment();      if (isLargeLayout) {         // The device is using a large layout, so show the fragment equally a dialog         newFragment.show(fragmentManager, "dialog");     } else {         // The device is smaller, and so testify the fragment fullscreen         FragmentTransaction transaction = fragmentManager.beginTransaction();         // For a little polish, specify a transition animation         transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);         // To make information technology fullscreen, use the 'content' root view equally the container         // for the fragment, which is always the root view for the activeness         transaction.add(android.R.id.content, newFragment)                    .addToBackStack(null).commit();     } }            

For more information about performing fragment transactions, run across the Fragments guide.

In this example, the mIsLargeLayout boolean specifies whether the current device should use the app's large layout design (and thus show this fragment as a dialog, rather than fullscreen). The best style to set this kind of boolean is to declare a bool resource value with an culling resource value for different screen sizes. For case, here are two versions of the bool resource for unlike screen sizes:

res/values/bools.xml

<!-- Default boolean values --> <resources>     <bool name="large_layout">false</bool> </resources>        

res/values-large/bools.xml

<!-- Big screen boolean values --> <resources>     <bool name="large_layout">true</bool> </resource>        

And then yous tin can initialize the mIsLargeLayout value during the activity's onCreate() method:

Kotlin

override fun onCreate(savedInstanceState: Bundle?) {     super.onCreate(savedInstanceState)     setContentView(R.layout.activity_main)      isLargeLayout = resources.getBoolean(R.bool.large_layout) }            

Java

boolean isLargeLayout;  @Override public void onCreate(Parcel savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);      isLargeLayout = getResources().getBoolean(R.bool.large_layout); }            

Showing an activeness as a dialog on large screens

Instead of showing a dialog as a fullscreen UI when on small screens, yous can accomplish the same result past showing an Activity as a dialog when on large screens. Which arroyo y'all choose depends on your app blueprint, but showing an activity as a dialog is ofttimes useful when your app is already designed for pocket-sized screens and you'd like to meliorate the experience on tablets by showing a brusk-lived activity as a dialog.

To show an activeness as a dialog just when on big screens, utilise the Theme.Holo.DialogWhenLarge theme to the <activity> manifest element:

<activity android:theme="@android:way/Theme.Holo.DialogWhenLarge" >        

For more information about styling your activities with themes, meet the Styles and Themes guide.

Dismissing a Dialog

When the user touches any of the action buttons created with an AlertDialog.Builder, the system dismisses the dialog for yous.

The organization as well dismisses the dialog when the user touches an item in a dialog list, except when the listing uses radio buttons or checkboxes. Otherwise, you lot can manually dismiss your dialog by calling dismiss() on your DialogFragment.

In case you need to perform certain actions when the dialog goes away, y'all tin can implement the onDismiss() method in your DialogFragment.

You can also cancel a dialog. This is a special event that indicates the user explicitly left the dialog without completing the task. This occurs if the user presses the Dorsum button, touches the screen exterior the dialog area, or if yous explicitly call abolish() on the Dialog (such as in response to a "Cancel" button in the dialog).

As shown in the example above, you can respond to the abolish effect by implementing onCancel() in your DialogFragment grade.

Annotation: The system calls onDismiss() upon each event that invokes the onCancel() callback. However, if y'all call Dialog.dismiss() or DialogFragment.dismiss(), the organisation calls onDismiss() simply non onCancel(). So you should more often than not call dismiss() when the user presses the positive push in your dialog in society to remove the dialog from view.

cordovarile1976.blogspot.com

Source: https://developer.android.com/guide/topics/ui/dialogs

0 Response to "How to Get a Dialog Box to Show Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel