Android dismiss all dialogs

Полный список

— рассматриваем обработчики событий диалога
— программно закрываем и показываем диалог

Мы закрываем диалог нажатием на кнопку, на пункт списка или кнопкой Назад. Давайте рассмотрим, какие есть программные способы закрытия. Также узнаем, какие обработчики диалога можно использовать, чтобы отследить закрытие.

Project name: P0661_AlertDialogOperations
Build Target: Android 2.3.3
Application name: AlertDialogOperations
Package name: ru.startandroid.develop.p0661alertdialogoperations
Create Activity: MainActivity

В strings.xml пропишем тексты:

Код в основном должен быть понятен по прошлым урокам. Создаем диалог, настраиваем заголовок, сообщение и одну кнопку без обработчика (нам он сейчас не нужен). Далее для диалога указываем три обработчика: отображения, отмены и закрытия диалога. Все они пишут о себе в лог.

onclick – обработчик кнопки из main.xml. Здесь мы просто запускаем диалог.

Обработчики

Давайте смотреть, когда и какие обработчики событий диалога будут срабатывать. Все сохраним и запустим. Жмем кнопку Диалог, появляется диалог.

Диалог создался и сработал обработчик отображения диалога. Нажмем кнопку ОК. Диалог закрылся, а лог показал следующее:

Сработал обработчик закрытия диалога.

Теперь еще раз запустим диалог кнопкой Диалог. В логе видим:

Метод onCreateDialog не отработал, т.к. диалог уже создан. Это мы подробно рассматривали в прошлых уроках. Сработал обработчик отображения.

Для закрытия диалога нажмем кнопку Back (Назад) на эмуляторе. В логе появились следующие строки:

Перед обработчиком закрытия (Dismiss) сработал обработчик отмены (Cancel), т.к. диалог был отменен.

Операции

Разберем программные методы управления диалогом. Для этого немного изменим код MainActivity.java. Добавим два пустых пока метода method1 и method2, и перепишем onclick:

Handler мы пока не проходили, его понимать необязательно. Сейчас просто надо принять, что вся эта конструкция в onclick покажет диалог, затем через 2 секунды выполнит метод method1 и еще через 2 секунды выполнит метод method2. Т.е. получится такая последовательность:

отображение диалога
2 сек
выполнение method1
2 сек
выполнение method2

dismiss

Мы будем работать с method1 и method2. Начнем с метода dismiss – он закрывает диалог. Перепишем метод method1:

method2 пока не трогаем. Запустим приложение и нажмем кнопку Диалог. Диалог появился, повисел две секунды и закрылся. Это нам обеспечил dismiss, вызванный через 2 секунды после отображения диалога. Смотрим лог:

Все верно. Диалог создался, отобразился и закрылся. Обратите внимание на время записей в логе. Между Show и Dismiss должно быть примерно 2 секунды.

cancel

Теперь используем метод cancel. Перепишем method1:

Все сохраним, запустим приложение и вызовем диалог. Снова диалог появился и закрылся через две секунды. Сработал метод cancel. Логи:

Create
Show
Cancel
Dismiss

Все так же, как при закрытии диалога кнопкой Back.

Снова перепишем method1, используя метод hide:

Запустим приложение, вызовем диалог. Он отобразился и закрылся. Смотрим лог:

На этот раз обработчик закрытия не сработал. Диалог просто скрылся. Зачем это нужно, я не знаю, но метод такой есть, поэтому я рассказал о нем.

Управление из Activity

Мы работали напрямую с объектом Dialog и вызывали его методы. Есть еще другой способ. Сначала немного теории о механизме взаимодействия Activity и диалога. Когда мы первый раз выполняем метод showDialog, мы передаем туда ID. Это ID далее передается в onCreateDialog. В итоге onCreateDialog возвращает созданный диалог, и Activity для себя увязывает его с ID. И если мы захотим обратиться к этому диалогу, нам нужен будет только ID, Activity сама по нему определит, какой диалог нам нужен.

Когда мы, например, следующие разы вызываем showDialog, мы передаем туда ID, но диалог не создается. Activity по ID находит ранее созданный диалог и показывает его. У Activity также есть методы по закрытию диалога – это dismissDialog и removeDialog. Первый просто закрывает диалог, а второй закрывает и заставляет Activity забыть про него. Т.е. когда мы в след.раз захотим показать этот диалог, Activity будет заново создавать его, а не брать уже готовый. Проверим это.

dismissDialog

Все сохраним и запустим. Вызовем диалог и ждем. Диалог отобразился, через 2 секунды закрылся, и еще через 2 снова открылся. Смотрим лог:

Когда диалог отобразился второй раз, не сработал метод его создания, т.к. Activity использовало созданный при первом вызове объект.

removeDialog

Перепишем метод method1:

Будем не только закрывать диалог, но и «забывать» его. method2 оставляем без изменений, он будет показывать диалог.

Запустим приложение, запустим диалог и ждем. Диалог открылся, закрылся и открылся снова. Смотрим лог:

Читайте также:  Дроид кам для андроида

Create
Show
Dismiss
Create
Show

Но на этот раз при втором показе он снова создавался, т.к. Activity его забыло благодаря методу removeDialog.

У объекта Dialog есть еще метод show. Чем он отличается от метода Activity showDialog? show просто покажет созданный диалог, а showDialog, начинает проверять был ли уже создан диалог, создает его, если необходимо, и вызывает для него метод onPrepareDialog.

На следующем уроке:

— работаем с ProgressDialog

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

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:

Читайте также:  Unable to locate local android sdk location did you run android studio after installing

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.

Источник

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