Close all dialogs android

How to close a Dialog in Android programmatically?

How do I close a Dialog in android programmatically for example by a button?

Imagine I have a Dialog with a OK button on it, and want to close it by OK button, but I cant do that!

I googled and found nothing useful, and almost all of them for closing AlertDialog not a Dialog.

5 Answers 5

You can call dismiss on the dialog.

This is an example of how to create a AlertDialog with 2 Buttons (OK and cancel). When clicking the cancel button,

is called to close the dialog.

From anywhere outside, you could call

Only this line will close it. 🙂

Implement it in the onClickListener.

You can use the methods cancel() or dismiss() . The method cancel() essentially the same as calling dismiss(), but it will also call your DialogInterface.OnCancelListener (if registered).

Alternative to the dismiss(); option, if you have your dialog as a separate Activity (s.a. DialogActivity ), another way to close it is to call:

Call this method inside the OnClickListener class’ onClick() method.

This will call the onPause() , onStop() and onDestroy() methods consequently and kill the current activity — same as Back button.

Источник

Android — How to Dismiss All Dialogs in onPause

I have an activity that could show different dialogs during run-time. I use onCreateDialog(int id) to create each dialog and I use showDialog(int id) and dismissDialog(int id) method show and dismiss each dialog respectively.

When onPause() is called, I don’t know which dialog (if any) is being displayed. I want to make sure that when onPause is called, all dialogs are dimissed. Is there a recommended way to dismiss all dialogs? Would I have to call dismissDialog() for each dialog?

6 Answers 6

If you are using DialogFragment and you want to dismiss all you can use:

Depending on how many dialog’s we’re talking about. The short answer is yes, you’ll have to dismiss each dialog.

There may be elegant ways of doing this other than simply having a few dialogs declared at the activity level. You could store all the dialogs in a HashMap once they are declared and then iterate through the list and close each one onPause.

Since you don’t know which are open you’ll need to go through and test or track the states.

However, if you truly have this many dialogs on your screen you may have some issues with your UI/UX design as Android should give you a model which makes it easy to implement it without what seems like poor design.

With android’s recent emphasis on using DialogFragment container you wil not need to call dismiss on each

Since the dialogs will have a Fragment container you may simply use their lifecycle. Consider this DialogFragment:

Which you will show in your activity using a fragmentmanager normally calling it like this:

Note that you may actually alter what the DialogFragment does in onPause. When your activity calls onPause, this onPause will be called too.

Dismissing the dialog in onPause() using this.dismiss() won’t do the work because once the activity resumes it will resume the dialog as well. (I think this is because the savestate is stored prior to onPause).

But you can safely dismiss the dialog(s) in onCreate if you detect a savedInstanceState (a resume) like shown in the code.

Источник

How to correctly dismiss a DialogFragment?

The docs say this for the dismiss() method from the Dialog class:

Dismiss this dialog, removing it from the screen. This method can be invoked safely from any thread. Note that you should not override this method to do cleanup when the dialog is dismissed, instead implement that in onStop() .

In my code, all I do is call getDialog().dismiss() to dismiss it. But I am not doing anything else or even using onStop() . So I am asking exactly how to correctly dismiss a DialogFragment to avoid any memory leaks, etc..

13 Answers 13

tl;dr: The correct way to close a DialogFragment is to use dismiss() directly on the DialogFragment.

Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.

Thus, you should not use getDialog().dismiss() , since that would invoke dismiss() on the dialog. Instead, you should use the dismiss() method of the DialogFragment itself:

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.

Читайте также:  Remove item from recyclerview android

As you can see, this takes care not only of closing the dialog but also of handling the fragment transactions involved in the process.

You only need to use onStop if you explicitly created any resources that require manual cleanup (closing files, closing cursors, etc.). Even then, I would override onStop of the DialogFragment rather than onStop of the underlying Dialog.

Источник

How do I close an Android alertdialog

I am developing a quiz and I need the user to answer all the questions before proceeding. When the user has not answered all the questions I display a simple alertdialog informing him or her. The problem is whatever I do I can’t get the alertdialog to close. Why isn’t dialog.cancel working?`This is the code:

15 Answers 15

The AlertDialog.Builder itself does not contain a dismiss() or cancel() method.

It is a convenience class to help you create a Dialog, which DOES have access to those methods.

Here is an example:

You can then call the alert.cancel() method on the alert (not the builder).

instead of using

Use setNegative button, no Positive button required! I promise you’ll win x

put this line in OnCreate()

and them use this variable in following code

Try this code.. It is running successfully..

Replying to an old post but hopefully somebody might find this useful. Do this instead

You can then go ahead and do,

The above code works but make sure you make alert a global variable so you can reach it from within the onClick method.

Just in case anyone was looking for the Kotlin version of this, it is as follows:

I would try putting a

before the dialog.dismiss() line in your code to see if it actually reaches that section.

Use Dialog instead of AlertDialog

AlertDialog doesn’t have dismiss() but AlertDialog has some methods for button like setPositiveButton() .

I recommend to use Dialog if you want customized dialog.

you can simply restart the activity where your alertdialog appear or another activity depend on your judgement. if you want to restart activity use this finish(); startActivity(getIntent());

I tried the solution of PowerAktar, but the AlertDialog and the Builder always kept seperate parts. So how to get the «true» AlertDialog?

I found my solutions in the show-Dialog: You write

to display the dialog. In the help of show it says «Creates a AlertDialog with the arguments supplied to this builder and Dialog.show()’s the dialog.» So the dialog is finally created here. The result of the show()-Command is the AlertDialog itself. So you can use this result:

With this adTrueDialog it is possible to cancel() .

or to execute a buttons command within the dialog:

Источник

Dialogs

In this document

Key classes

See also

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

Dialog Design

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

The Dialog class is the base class for dialogs, but you should avoid instantiating Dialog directly. Instead, use one of the following subclasses:

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

Avoid ProgressDialog

Android includes another dialog class called ProgressDialog that shows a dialog with a progress bar. However, if you need to indicate loading or indeterminate progress, you should instead follow the design guidelines for Progress & Activity and use a ProgressBar in your layout.

These classes define the style and structure for your dialog, but you should use 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 Back button or rotates the screen. The DialogFragment class also 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 appear 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 date or time picker, you should instead read the Pickers guide.

Note: Because the DialogFragment class was originally added with Android 3.0 (API level 11), this document describes how to use the DialogFragment class that’s 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 1.6 or higher. If the minimum version your app supports is API level 11 or higher, then you can use the framework version of DialogFragment , but be aware that the links in this document are for the support library APIs. When using the support library, be sure that you import android.support.v4.app.DialogFragment class and not android.app.DialogFragment .

Читайте также:  Форплей для телевизора андроид

Creating a Dialog Fragment

You can accomplish a wide variety of dialog designs—including custom layouts and those described in the Dialogs design guide—by extending DialogFragment and creating a AlertDialog in the onCreateDialog() callback method.

For example, here’s a basic AlertDialog that’s managed within a DialogFragment :

Figure 1. A dialog with a message and two action buttons.

Now, when you create an instance of this class and call show() on that object, the dialog appears as shown in figure 1.

The next section describes more about using the AlertDialog.Builder APIs to create the dialog.

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

Building an Alert Dialog

The AlertDialog class allows you to build a variety of dialog designs and is often the only dialog class you’ll need. As shown in figure 2, there are three regions of an alert dialog:

Figure 2. The layout of a dialog.

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 need to state a simple message or question (such as the dialog in figure 1), you don’t need a title.
Content area

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

There should be no more than 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.

The following topics show how to define various dialog attributes using the AlertDialog.Builder class.

Adding buttons

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

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

There are three different action buttons you can add:

Positive You should use this to accept and continue with the action (the «OK» action). Negative You should use this to cancel the action. Neutral You should use this when the user may not want to proceed with the action, but doesn’t necessarily want to cancel. It appears between the positive and negative buttons. For example, the action might be «Remind me later.»

You can add only one of each button type to an AlertDialog . That is, you cannot have more than one «positive» button.

Figure 3. A dialog with a title and list.

Adding a list

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

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

To create a single-choice list like the one in figure 3, use the setItems() method:

Because the list appears in the dialog’s content area, the dialog cannot show both a message and a list and you should set a title for the dialog with setTitle() . To specify the items for the list, call setItems() , passing an array. Alternatively, you can specify a list using setAdapter() . This allows you to back the list 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: By default, touching a list item dismisses the dialog, unless you’re using one of the following persistent choice lists.

Figure 4. A list of multiple-choice items.

Adding a persistent multiple-choice or single-choice list

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

For example, here’s how you can create a multiple-choice list like the one shown in figure 4 that saves the selected items in an ArrayList :

Although both a traditional list and a list with radio buttons provide a «single choice» action, you should use setSingleChoiceItems() if you want to persist the user’s choice. That is, if opening the dialog again later should indicate what the user’s current choice is, then you create a list with radio buttons.

Creating a Custom Layout

Figure 5. 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 can still use AlertDialog.Builder methods to add buttons and a title.

For example, here’s the layout file for the dialog in Figure 5:

Tip: By default, when you set an EditText element to use the «textPassword» input type, the font family is set to monospace, so you should change 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 call setView() to place the layout in the dialog.

Читайте также:  Подскажите видеоредактор для андроид

Tip: If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in the manifest element:

That’s it. 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 item from its list, your DialogFragment might perform the necessary action itself, but often you’ll want to deliver the event 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 example, here’s a DialogFragment that defines an interface through which it delivers the events back to the host activity:

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

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:

Showing a Dialog

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

The second argument, «missiles» , 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 as an Embedded Fragment

You might have a UI design in which you want a piece of the UI to appear as a dialog in some situations, but as a full screen or embedded fragment in others (perhaps depending on whether the device is a large screen or small screen). The DialogFragment class offers you this flexibility because it can still behave as an embeddable Fragment .

However, you cannot use AlertDialog.Builder or other Dialog objects to build the dialog in this case. If you want the DialogFragment to be embeddable, you must define the dialog’s UI in a layout, then load the layout in the onCreateView() callback.

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

And here’s some code that decides whether to show the fragment as a dialog or a fullscreen UI, based on the screen size:

For more information about performing fragment transactions, see 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 way to set this kind of boolean is to declare a bool resource value with an alternative resource value for different screen sizes. For example, here are two versions of the bool resource for different screen sizes:

Then you can initialize the mIsLargeLayout value during the activity’s onCreate() method:

Showing an activity as a dialog on large screens

Instead of showing a dialog as a fullscreen UI when on small screens, you can accomplish the same result by showing an Activity as a dialog when on large screens. Which approach you choose depends on your app design, but showing an activity as a dialog is often useful when your app is already designed for small screens and you’d like to improve the experience on tablets by showing a short-lived activity as a dialog.

To show an activity as a dialog only when on large screens, apply the Theme.Holo.DialogWhenLarge theme to the manifest element:

For more information about styling your activities with themes, see 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 you.

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

In case you need to perform certain actions when the dialog goes away, you 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 Back button, touches the screen outside the dialog area, or if you explicitly call cancel() 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 cancel event by implementing onCancel() in your DialogFragment class.

Источник

Оцените статью