- Диалоговые окна
- Общая информация
- Класс Dialog
- Методы onCreateDialog() и onPrepareDialog()
- Диалоговое окно AlertDialog
- AlertDialog с ссылкой
- Dialogs
- In this document
- Key classes
- See also
- Avoid ProgressDialog
- Creating a Dialog Fragment
- Building an Alert Dialog
- Adding buttons
- Adding a list
- Adding a persistent multiple-choice or single-choice list
- Creating a Custom Layout
- Passing Events Back to the Dialog’s Host
- Showing a Dialog
- Showing a Dialog Fullscreen or as an Embedded Fragment
- Showing an activity as a dialog on large screens
- Dismissing a Dialog
Диалоговые окна
Начиная с Android 3.0, работа с диалоговыми окнами чуть изменилась. С тех пор статья не переписывалась и могла морально устареть.
Общая информация
В некоторых случаях требуется показать диалоговое окно, где пользователю нужно сделать какой-нибудь выбор или показать сообщение об ошибке. Безусловно, можно создать собственное окно, расположить в нем нужные кнопки и обрабатывать их нажатия. Но, в Android уже есть собственные встроенные диалоговые окна, которые гибко настраиваются под задачи. Использование диалоговых окон для простых задач позволяет сократить число классов Activity в приложении, экономя ресурсы памяти. Ведь вам не придётся регистрировать активность в манифесте, думать над компоновкой элементов на экране и так далее.
Диалоговые окна в Android представляют собой полупрозрачные «плавающие» активности, частично перекрывающие родительский экран, из которого их вызвали. Как правило, они затеняют родительскую активность позади себя с помощью фильтров размывания или затемнения. Вы можете установить заголовок с помощью метода setTitle() и содержимое с помощью метода setContentView().
Android поддерживает следующие типы диалоговых окон:
- Dialog — базовый класс для всех типов диалоговых окон;
- AlertDialog — диалоговое окно с кнопками, списком, флажками или переключателями;
- CharacterPickerDialog — диалоговое окно, позволяющее выбрать символ с ударением, связанный с базовым символом;
- ProgressDiaiog — диалоговое окно с индикатором прогресса при помощи компонента ProgressBar. В API 26 признан устаревшим.
- DatePickerDialog — диалоговое окно выбора даты с элементом DatePicker
- TimePickerDialog — диалоговое окно выбора времени с элементом TimePicker
Если ни один из существующих типов диалоговых окон вам не подходит, то можете создать своё собственное диалоговое окно.
Класс Dialog
Класс Dialog является базовым для всех классов диалоговых окон. Поскольку ProgressDialog, TimePickerDialog И DatePickerDialog — расширение класса AlertDialog, они также могут иметь командные кнопки.
Каждое диалоговое окно должно быть определено внутри активности или фрагмента, в которых будет использоваться. Диалоговое окно можно открыть один раз или несколько раз.
Для отображения диалогового окна необходимо вызвать метод showDialog() и передать ему в качестве параметра идентификатор диалога (константа, которую надо объявить в коде программы), который вы хотите отобразить.
Метод dismissDialog() прячет диалоговое окно (но не удаляет), не отображая его на экране. Окно остаётся в пуле диалоговых окон данной активности. При повторном отображении при помощи метода showDialog() будет использована кэшированная версия окна.
Метод removeDialog() удаляет диалоговое окно из пула окон данной активности. При повторном вызове метода showDialog() диалоговое окно придётся создавать снова.
Рассмотрим базовый пример создания диалогового окна на основе класса Dialog. Создайте простейшую разметку для диалогового окна — текстовое поле внутри LinearLayout. В разметку главной активности добавьте кнопку для вызова диалогового окна. В коде для главной активности напишем:
По умолчанию при показе диалогового окна главная активность затемняется. В документации есть константы, позволяющие управлять степенью затемнения:
На эмуляторе я не заметил разницы. В старой версии Android 2.3 был ещё эффект размытия WindowManager.LayoutParams.FLAG_BLUR_BEHIND, который теперь считается устаревшим. Если вы по упрямству всё равно пропишите данный эффект, то получите не эффект размытия, а чёрный фон. Кто знает, может вас устроит данный вариант.
Методы onCreateDialog() и onPrepareDialog()
Метод onCreateDialog() вызывается один раз при создании окна. После начального создания при каждом вызове метода showDialog() будет срабатывать обработчик onPrepareDialog(). Переопределив этот метод, вы можете изменять диалоговое окно при каждом его выводе на экран. Это позволит привнести контекст в любое из отображаемых значений. Если требуется перед каждым вызовом диалогового окна изменять его свойства (например, текстовое сообщение или количество кнопок), то можно реализовать внутри этого метода. В этот метод передают идентификатор диалога и сам объект Dialog, который был создан в методе onCreateDialog().
Так как в одном приложении может быть несколько диалоговых окон, то необходимо заранее определить диалоговое окно, которое будет использоваться в активности. Для этого создаётся идентификатор (константа с целым числом). При вызове метода showDialog() вы передаёте данный идентификатор диалогового окна в качестве параметра. После этого идёт вызов метода onCreateDialog(), который возвращает экземпляр нужного диалогового окна.
Можно создавать диалог без onCreateDialog(), например в обработчике нажатия кнопки вызова диалога, но тогда он не будет присоединён к текущей активности. Чтобы прикрепить его к активности, необходимо вызвать метод setOwnerActivity(), передав ему в качестве параметра текущую активность.
Перейдём к примеру. Если в активности должны вызываться несколько различных диалоговых окон, сначала необходимо определить целочисленный идентификатор для каждого диалога, например:
Эти идентификаторы потом можно использовать в вызове метода showDialog() и в обработчике события onCreateDialog() в операторе switch:
Следует отметить, что методы Activity.onCreateDialog() и Activity.onPrepareDialog() устарели. Используйте DialogFragment.
Диалоговое окно AlertDialog
Примеры создания диалоговых окон типа AlertDialog рассмотрены в этой статье
AlertDialog с ссылкой
Практического смысла возможно не имеет, но можно сделать текст сообщения ссылкой.
Источник
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.
Источник