Added in API level 17

Presentation


open class Presentation : Dialog

Base class for presentations.

A presentation is a special kind of dialog whose purpose is to present content on a secondary display. A Presentation is associated with the target Display at creation time and configures its context and resource configuration according to the display's metrics.

Notably, the Context of a presentation is different from the context of its containing Activity. It is important to inflate the layout of a presentation and load other resources using the presentation's own context to ensure that assets of the correct size and density for the target display are loaded.

A presentation is automatically canceled (see Dialog.cancel()) when the display to which it is attached is removed. An activity should take care of pausing and resuming whatever content is playing within the presentation whenever the activity itself is paused or resumed.

Choosing a presentation display

Before showing a Presentation it's important to choose the Display on which it will appear. Choosing a presentation display is sometimes difficult because there may be multiple displays attached. Rather than trying to guess which display is best, an application should let the system choose a suitable presentation display.

There are two main ways to choose a Display.

Using the media router to choose a presentation display

The easiest way to choose a presentation display is to use the MediaRouter API. The media router service keeps track of which audio and video routes are available on the system. The media router sends notifications whenever routes are selected or unselected or when the preferred presentation display of a route changes. So an application can simply watch for these notifications and show or dismiss a presentation on the preferred presentation display automatically.

The preferred presentation display is the display that the media router recommends that the application should use if it wants to show content on the secondary display. Sometimes there may not be a preferred presentation display in which case the application should show its content locally without using a presentation.

Here's how to use the media router to create and show a presentation on the preferred presentation display using android.media.MediaRouter.RouteInfo#getPresentationDisplay().

MediaRouter mediaRouter = (MediaRouter) context.getSystemService(Context.MEDIA_ROUTER_SERVICE);
  MediaRouter.RouteInfo route = mediaRouter.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_VIDEO);
  if (route != null) {
      Display presentationDisplay = route.getPresentationDisplay();
      if (presentationDisplay != null) {
          Presentation presentation = new MyPresentation(context, presentationDisplay);
          presentation.show();
      }
  }

The following sample code from ApiDemos demonstrates how to use the media router to automatically switch between showing content in the main activity and showing the content in a presentation when a presentation display is available.

Using the display manager to choose a presentation display

Another way to choose a presentation display is to use the DisplayManager API directly. The display manager service provides functions to enumerate and describe all displays that are attached to the system including displays that may be used for presentations.

The display manager keeps track of all displays in the system. However, not all displays are appropriate for showing presentations. For example, if an activity attempted to show a presentation on the main display it might obscure its own content (it's like opening a dialog on top of your activity). Creating a presentation on the main display will result in android.view.WindowManager.InvalidDisplayException being thrown when invoking show().

Here's how to identify suitable displays for showing presentations using DisplayManager.getDisplays(String) and the DisplayManager.DISPLAY_CATEGORY_PRESENTATION category.

DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
  Display[] presentationDisplays = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION);
  if (presentationDisplays.length > 0) {
      // If there is more than one suitable presentation display, then we could consider
      // giving the user a choice.  For this example, we simply choose the first display
      // which is the one the system recommends as the preferred presentation display.
      Display display = presentationDisplays[0];
      Presentation presentation = new MyPresentation(context, presentationDisplay);
      presentation.show();
  }

The following sample code from ApiDemos demonstrates how to use the display manager to enumerate displays and show content on multiple presentation displays simultaneously.

Summary

Inherited constants
Int BUTTON1

Int BUTTON2

Int BUTTON3

Int BUTTON_NEGATIVE

The identifier for the negative button.

Int BUTTON_NEUTRAL

The identifier for the neutral button.

Int BUTTON_POSITIVE

The identifier for the positive button.

Public constructors
Presentation(outerContext: Context!, display: Display!)

Creates a new presentation that is attached to the specified display using the default theme.

Presentation(outerContext: Context!, display: Display!, theme: Int)

Creates a new presentation that is attached to the specified display using the optionally specified theme.

Public methods
open Display!

Gets the Display that this presentation appears on.

open Resources!

Gets the Resources that should be used to inflate the layout of this presentation.

open Unit

Called by the system when the properties of the Display to which the presentation is attached have changed.

open Unit

Called by the system when the Display to which the presentation is attached has been removed.

open Unit

Inherited from Dialog.show.

Protected methods
open Unit

open Unit

Inherited functions
Unit addContentView(view: View, params: ViewGroup.LayoutParams?)

Add an additional content view to the screen. Added after any existing ones in the screen -- existing views are NOT removed.

Unit cancel()

Cancel the dialog. This is essentially the same as calling dismiss(), but it will also call your DialogInterface.OnCancelListener (if registered).

Unit closeOptionsMenu()

Unit create()

Forces immediate creation of the dialog.

Note that you should not override this method to perform dialog creation. Rather, override onCreate(android.os.Bundle).

Unit dismiss()

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.

Boolean dispatchGenericMotionEvent(ev: MotionEvent)

Called to process generic motion events. You can override this to intercept all generic motion events before they are dispatched to the window. Be sure to call this implementation for generic motion events that should be handled normally.

Boolean dispatchKeyEvent(event: KeyEvent)

Called to process key events. You can override this to intercept all key events before they are dispatched to the window. Be sure to call this implementation for key events that should be handled normally.

Boolean dispatchKeyShortcutEvent(event: KeyEvent)

Called to process a key shortcut event. You can override this to intercept all key shortcut events before they are dispatched to the window. Be sure to call this implementation for key shortcut events that should be handled normally.

Boolean dispatchPopulateAccessibilityEvent(event: AccessibilityEvent)

Called to process population of AccessibilityEvents.

Boolean dispatchTouchEvent(ev: MotionEvent)

Called to process touch screen events. You can override this to intercept all touch screen events before they are dispatched to the window. Be sure to call this implementation for touch screen events that should be handled normally.

Boolean dispatchTrackballEvent(ev: MotionEvent)

Called to process trackball events. You can override this to intercept all trackball events before they are dispatched to the window. Be sure to call this implementation for trackball events that should be handled normally.

T findViewById(id: Int)

Finds the first descendant view with the given ID or null if the ID is invalid (< 0), there is no matching view in the hierarchy, or the dialog has not yet been fully created (for example, via show() or create()).

Note: In most cases -- depending on compiler support -- the resulting view is automatically cast to the target class type. If the target class type is unconstrained, an explicit cast may be necessary.

ActionBar? getActionBar()

Retrieve the ActionBar attached to this dialog, if present.

Context getContext()

Retrieve the Context this Dialog is running in.

View? getCurrentFocus()

Call android.view.Window#getCurrentFocus on the Window if this Activity to return the currently focused view.

LayoutInflater getLayoutInflater()

OnBackInvokedDispatcher getOnBackInvokedDispatcher()

Returns the OnBackInvokedDispatcher instance associated with the window that this dialog is attached to.

Activity? getOwnerActivity()

Returns the Activity that owns this Dialog. For example, if Activity.showDialog(int) is used to show this Dialog, that Activity will be the owner (by default). Depending on how this dialog was created, this may return null.

SearchEvent? getSearchEvent()

During the onSearchRequested() callbacks, this function will return the SearchEvent that triggered the callback, if it exists.

Int getVolumeControlStream()

Window? getWindow()

Retrieve the current Window for the activity. This can be used to directly access parts of the Window API that are not available through Activity/Screen.

Unit hide()

Hide the dialog, but do not dismiss it.

Unit invalidateOptionsMenu()

Boolean isShowing()

Unit onActionModeFinished(mode: ActionMode!)

Called when an action mode has been finished. The appropriate mode callback method will have already been invoked. Note that if you override this method you should always call through to the superclass implementation by calling super.onActionModeFinished(mode).
If you override this method you must call through to the superclass implementation.

Unit onActionModeStarted(mode: ActionMode!)

Called when an action mode has been started. The appropriate mode callback method will have already been invoked. Note that if you override this method you should always call through to the superclass implementation by calling super.onActionModeStarted(mode).
If you override this method you must call through to the superclass implementation.

Unit onAttachedToWindow()

Unit onBackPressed()

Called when the dialog has detected the user's press of the back key. The default implementation simply cancels the dialog (only if it is cancelable), but you can override this to do whatever you want.

If you target version android.os.Build.VERSION_CODES#TIRAMISU or later, you should not use this method but register an OnBackInvokedCallback on an OnBackInvokedDispatcher that you can retrieve using getOnBackInvokedDispatcher(). You should also set android:enableOnBackInvokedCallback="true" in the application manifest.

Alternatively, you can use androidx.activity.ComponentDialog#getOnBackPressedDispatcher() for backward compatibility.

Unit onContentChanged()

Boolean onContextItemSelected(item: MenuItem)

Unit onContextMenuClosed(menu: Menu)

Unit onCreate(savedInstanceState: Bundle!)

Similar to android.app.Activity#onCreate, you should initialize your dialog in this method, including calling #setContentView.

Unit onCreateContextMenu(menu: ContextMenu!, v: View!, menuInfo: ContextMenu.ContextMenuInfo!)

Boolean onCreateOptionsMenu(menu: Menu)

It is usually safe to proxy this call to the owner activity's Activity.onCreateOptionsMenu(Menu) if the client desires the same menu for this Dialog.

Boolean onCreatePanelMenu(featureId: Int, menu: Menu)

View? onCreatePanelView(featureId: Int)

Unit onDetachedFromWindow()

Boolean onGenericMotionEvent(event: MotionEvent)

Called when a generic motion event was not handled by any of the views inside of the dialog.

Generic motion events describe joystick movements, mouse hovers, track pad touches, scroll wheel movements and other input events. The source of the motion event specifies the class of input that was received. Implementations of this method must examine the bits in the source before processing the event. The following code example shows how this is done.

Generic motion events with source class android.view.InputDevice#SOURCE_CLASS_POINTER are delivered to the view under the pointer. All other generic motion events are delivered to the focused view.

See View.onGenericMotionEvent(MotionEvent) for an example of how to handle this event.

Boolean onKeyDown(keyCode: Int, event: KeyEvent)

A key was pressed down.

If the focused view didn't want this event, this method is called.

Default implementation consumes KEYCODE_BACK and, as of P, KEYCODE_ESCAPE to later handle them in onKeyUp.

Boolean onKeyLongPress(keyCode: Int, event: KeyEvent)

Default implementation of KeyEvent.Callback.onKeyLongPress(): always returns false (doesn't handle the event).

Boolean onKeyMultiple(keyCode: Int, repeatCount: Int, event: KeyEvent)

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).

Boolean onKeyShortcut(keyCode: Int, event: KeyEvent)

Called when a key shortcut event is not handled by any of the views in the Dialog. Override this method to implement global key shortcuts for the Dialog. Key shortcuts can also be implemented by setting the shortcut property of menu items.

Boolean onKeyUp(keyCode: Int, event: KeyEvent)

A key was released.

Default implementation consumes KEYCODE_BACK and, as of P, KEYCODE_ESCAPE to close the dialog.

Boolean onMenuItemSelected(featureId: Int, item: MenuItem)

Boolean onMenuOpened(featureId: Int, menu: Menu)

Boolean onOptionsItemSelected(item: MenuItem)

Unit onOptionsMenuClosed(menu: Menu)

Unit onPanelClosed(featureId: Int, menu: Menu)

Boolean onPrepareOptionsMenu(menu: Menu)

It is usually safe to proxy this call to the owner activity's Activity.onPrepareOptionsMenu(Menu) if the client desires the same menu for this Dialog.

Boolean onPreparePanel(featureId: Int, view: View?, menu: Menu)

Unit onRestoreInstanceState(savedInstanceState: Bundle)

Restore the state of the dialog from a previously saved bundle. The default implementation restores the state of the dialog's view hierarchy that was saved in the default implementation of onSaveInstanceState(), so be sure to call through to super when overriding unless you want to do all restoring of state yourself.

Bundle onSaveInstanceState()

Saves the state of the dialog into a bundle. The default implementation saves the state of its view hierarchy, so you'll likely want to call through to super if you override this to save additional state.

Boolean onSearchRequested()

This hook is called when the user signals the desire to start a search.

Boolean onSearchRequested(searchEvent: SearchEvent)

This hook is called when the user signals the desire to start a search.

Boolean onTouchEvent(event: MotionEvent)

Called when a touch screen event was not handled by any of the views under it. This is most useful to process touch events that happen outside of your window bounds, where there is no view to receive it.

Boolean onTrackballEvent(event: MotionEvent)

Called when the trackball was moved and not handled by any of the views inside of the activity. So, for example, if the trackball moves while focus is on a button, you will receive a call here because buttons do not normally do anything with trackball events. The call here happens before trackball movements are converted to DPAD key events, which then get sent back to the view hierarchy, and will be processed at the point for things like focus navigation.

Unit onWindowAttributesChanged(params: WindowManager.LayoutParams!)

Unit onWindowFocusChanged(hasFocus: Boolean)

ActionMode? onWindowStartingActionMode(callback: ActionMode.Callback!)

ActionMode? onWindowStartingActionMode(callback: ActionMode.Callback!, type: Int)

Unit openContextMenu(view: View)

Unit openOptionsMenu()

Unit registerForContextMenu(view: View)

Boolean requestWindowFeature(featureId: Int)

Enable extended window features. This is a convenience for calling getWindow().requestFeature().

T requireViewById(id: Int)

Finds the first descendant view with the given ID or throws an IllegalArgumentException if the ID is invalid (< 0), there is no matching view in the hierarchy, or the dialog has not yet been fully created (for example, via show() or create()).

Note: In most cases -- depending on compiler support -- the resulting view is automatically cast to the target class type. If the target class type is unconstrained, an explicit cast may be necessary.

Unit setCancelMessage(msg: Message?)

Set a message to be sent when the dialog is canceled.

Unit setCancelable(flag: Boolean)

Sets whether this dialog is cancelable with the BACK key.

Unit setCanceledOnTouchOutside(cancel: Boolean)

Sets whether this dialog is canceled when touched outside the window's bounds. If setting to true, the dialog is set to be cancelable if not already set.

Unit setContentView(view: View)

Set the screen content to an explicit view. This view is placed directly into the screen's view hierarchy. It can itself be a complex view hierarchy.

Unit setContentView(view: View, params: ViewGroup.LayoutParams?)

Set the screen content to an explicit view. This view is placed directly into the screen's view hierarchy. It can itself be a complex view hierarchy.

Unit setContentView(layoutResID: Int)

Set the screen content from a layout resource. The resource will be inflated, adding all top-level views to the screen.

Unit setDismissMessage(msg: Message?)

Set a message to be sent when the dialog is dismissed.

Unit setFeatureDrawable(featureId: Int, drawable: Drawable?)

Convenience for calling android.view.Window#setFeatureDrawable(int, Drawable).

Unit setFeatureDrawableAlpha(featureId: Int, alpha: Int)

Convenience for calling android.view.Window#setFeatureDrawableAlpha.

Unit setFeatureDrawableResource(featureId: Int, resId: Int)

Convenience for calling android.view.Window#setFeatureDrawableResource.

Unit setFeatureDrawableUri(featureId: Int, uri: Uri?)

Convenience for calling android.view.Window#setFeatureDrawableUri.

Unit setOnCancelListener(listener: DialogInterface.OnCancelListener?)

Set a listener to be invoked when the dialog is canceled.

This will only be invoked when the dialog is canceled. Cancel events alone will not capture all ways that the dialog might be dismissed. If the creator needs to know when a dialog is dismissed in general, use setOnDismissListener.

Unit setOnDismissListener(listener: DialogInterface.OnDismissListener?)

Set a listener to be invoked when the dialog is dismissed.

Unit setOnKeyListener(onKeyListener: DialogInterface.OnKeyListener?)

Sets the callback that will be called if a key is dispatched to the dialog.

Unit setOnShowListener(listener: DialogInterface.OnShowListener?)

Sets a listener to be invoked when the dialog is shown.

Unit setOwnerActivity(activity: Activity)

Sets the Activity that owns this dialog. An example use: This Dialog will use the suggested volume control stream of the Activity.

Unit setTitle(titleId: Int)

Set the title text for this dialog's window. The text is retrieved from the resources with the supplied identifier.

Unit setTitle(title: CharSequence?)

Set the title text for this dialog's window.

Unit setVolumeControlStream(streamType: Int)

By default, this will use the owner Activity's suggested stream type.

Unit takeKeyEvents(get: Boolean)

Request that key events come to this dialog. Use this if your dialog has no views with focus, but the dialog still wants a chance to process key events.

Unit unregisterForContextMenu(view: View)

Unit onPointerCaptureChanged(hasCapture: Boolean)

Called when pointer capture is enabled or disabled for the current window.

Unit onProvideKeyboardShortcuts(data: MutableList<KeyboardShortcutGroup!>!, menu: Menu?, deviceId: Int)

Called when Keyboard Shortcuts are requested for the current window.

Public constructors

Presentation

Added in API level 17
Presentation(
    outerContext: Context!,
    display: Display!)

Creates a new presentation that is attached to the specified display using the default theme.

Parameters
outerContext Context!: The context of the application that is showing the presentation. The presentation will create its own context (see getContext()) based on this context and information about the associated display.
display Display!: The display to which the presentation should be attached.

Presentation

Added in API level 17
Presentation(
    outerContext: Context!,
    display: Display!,
    theme: Int)

Creates a new presentation that is attached to the specified display using the optionally specified theme.

Parameters
outerContext Context!: The context of the application that is showing the presentation. The presentation will create its own context (see getContext()) based on this context and information about the associated display. From android.os.Build.VERSION_CODES#S, the presentation will create its own window context based on this context, information about the associated display. Customizing window type by getWindow#setType(int) causes the mismatch of the window and the created window context, which leads to android.view.WindowManager.InvalidDisplayException when invoking show().
display Display!: The display to which the presentation should be attached.
theme Int: A style resource describing the theme to use for the window. See Style and Theme Resources for more information about defining and using styles. This theme is applied on top of the current theme in outerContext. If 0, the default presentation theme will be used.

Public methods

getDisplay

Added in API level 17
open fun getDisplay(): Display!

Gets the Display that this presentation appears on.

Return
Display! The display.

getResources

Added in API level 17
open fun getResources(): Resources!

Gets the Resources that should be used to inflate the layout of this presentation. This resources object has been configured according to the metrics of the display that the presentation appears on.

Return
Resources! The presentation resources object.

onDisplayChanged

Added in API level 17
open fun onDisplayChanged(): Unit

Called by the system when the properties of the Display to which the presentation is attached have changed.

See Also

onDisplayRemoved

Added in API level 17
open fun onDisplayRemoved(): Unit

Called by the system when the Display to which the presentation is attached has been removed. The system automatically calls cancel to dismiss the presentation after sending this event.

See Also

show

Added in API level 17
open fun show(): Unit

Inherited from Dialog.show. Will throw android.view.WindowManager.InvalidDisplayException if the specified secondary Display can't be found or if it does not have Display.FLAG_PRESENTATION set.

Protected methods

onStart

Added in API level 17
protected open fun onStart(): Unit

onStop

Added in API level 17
protected open fun onStop(): Unit