• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.app;
18 
19 import android.annotation.CallSuper;
20 import android.annotation.DrawableRes;
21 import android.annotation.IdRes;
22 import android.annotation.LayoutRes;
23 import android.annotation.NonNull;
24 import android.annotation.Nullable;
25 import android.annotation.StringRes;
26 import android.annotation.StyleRes;
27 import android.annotation.UiContext;
28 import android.compat.annotation.UnsupportedAppUsage;
29 import android.content.ComponentName;
30 import android.content.Context;
31 import android.content.ContextWrapper;
32 import android.content.DialogInterface;
33 import android.content.pm.ApplicationInfo;
34 import android.content.res.Configuration;
35 import android.content.res.Resources;
36 import android.graphics.drawable.Drawable;
37 import android.net.Uri;
38 import android.os.Build;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.Looper;
42 import android.os.Message;
43 import android.util.Log;
44 import android.util.TypedValue;
45 import android.view.ActionMode;
46 import android.view.ContextMenu;
47 import android.view.ContextMenu.ContextMenuInfo;
48 import android.view.ContextThemeWrapper;
49 import android.view.Gravity;
50 import android.view.KeyEvent;
51 import android.view.LayoutInflater;
52 import android.view.Menu;
53 import android.view.MenuItem;
54 import android.view.MotionEvent;
55 import android.view.SearchEvent;
56 import android.view.View;
57 import android.view.View.OnCreateContextMenuListener;
58 import android.view.ViewGroup;
59 import android.view.ViewGroup.LayoutParams;
60 import android.view.Window;
61 import android.view.WindowManager;
62 import android.view.accessibility.AccessibilityEvent;
63 import android.window.OnBackInvokedCallback;
64 import android.window.OnBackInvokedDispatcher;
65 import android.window.WindowOnBackInvokedDispatcher;
66 
67 import com.android.internal.R;
68 import com.android.internal.app.WindowDecorActionBar;
69 import com.android.internal.policy.PhoneWindow;
70 
71 import java.lang.ref.WeakReference;
72 
73 /**
74  * Base class for Dialogs.
75  *
76  * <p>Note: Activities provide a facility to manage the creation, saving and
77  * restoring of dialogs. See {@link Activity#onCreateDialog(int)},
78  * {@link Activity#onPrepareDialog(int, Dialog)},
79  * {@link Activity#showDialog(int)}, and {@link Activity#dismissDialog(int)}. If
80  * these methods are used, {@link #getOwnerActivity()} will return the Activity
81  * that managed this dialog.
82  *
83  * <p>Often you will want to have a Dialog display on top of the current
84  * input method, because there is no reason for it to accept text.  You can
85  * do this by setting the {@link WindowManager.LayoutParams#FLAG_ALT_FOCUSABLE_IM
86  * WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM} window flag (assuming
87  * your Dialog takes input focus, as it the default) with the following code:
88  *
89  * <pre>
90  * getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
91  *         WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);</pre>
92  *
93  * <div class="special reference">
94  * <h3>Developer Guides</h3>
95  * <p>For more information about creating dialogs, read the
96  * <a href="{@docRoot}guide/topics/ui/dialogs.html">Dialogs</a> developer guide.</p>
97  * </div>
98  */
99 public class Dialog implements DialogInterface, Window.Callback,
100         KeyEvent.Callback, OnCreateContextMenuListener, Window.OnWindowDismissedCallback {
101     private static final String TAG = "Dialog";
102     @UnsupportedAppUsage
103     private Activity mOwnerActivity;
104 
105     private final WindowManager mWindowManager;
106 
107     @UnsupportedAppUsage
108     @UiContext
109     final Context mContext;
110     @UnsupportedAppUsage
111     final Window mWindow;
112 
113     View mDecor;
114 
115     private ActionBar mActionBar;
116     /**
117      * This field should be made private, so it is hidden from the SDK.
118      * {@hide}
119      */
120     protected boolean mCancelable = true;
121 
122     private String mCancelAndDismissTaken;
123     @UnsupportedAppUsage
124     private Message mCancelMessage;
125     @UnsupportedAppUsage
126     private Message mDismissMessage;
127     @UnsupportedAppUsage
128     private Message mShowMessage;
129 
130     @UnsupportedAppUsage
131     private OnKeyListener mOnKeyListener;
132 
133     private boolean mCreated = false;
134     @UnsupportedAppUsage
135     private boolean mShowing = false;
136     private boolean mCanceled = false;
137 
138     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
139     private final Handler mHandler = new Handler();
140 
141     private static final int DISMISS = 0x43;
142     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
143     private static final int CANCEL = 0x44;
144     private static final int SHOW = 0x45;
145 
146     @UnsupportedAppUsage
147     private final Handler mListenersHandler;
148 
149     private SearchEvent mSearchEvent;
150 
151     private ActionMode mActionMode;
152 
153     private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
154 
155     private final Runnable mDismissAction = this::dismissDialog;
156 
157     /** A {@link Runnable} to run instead of dismissing when {@link #dismiss()} is called. */
158     private Runnable mDismissOverride;
159     private OnBackInvokedCallback mDefaultBackCallback;
160 
161     /**
162      * Creates a dialog window that uses the default dialog theme.
163      * <p>
164      * The supplied {@code context} is used to obtain the window manager and
165      * base theme used to present the dialog.
166      *
167      * @param context the context in which the dialog should run
168      * @see android.R.styleable#Theme_dialogTheme
169      */
Dialog(@iContext @onNull Context context)170     public Dialog(@UiContext @NonNull Context context) {
171         this(context, 0, true);
172     }
173 
174     /**
175      * Creates a dialog window that uses a custom dialog style.
176      * <p>
177      * The supplied {@code context} is used to obtain the window manager and
178      * base theme used to present the dialog.
179      * <p>
180      * The supplied {@code theme} is applied on top of the context's theme. See
181      * <a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">
182      * Style and Theme Resources</a> for more information about defining and
183      * using styles.
184      *
185      * @param context the context in which the dialog should run
186      * @param themeResId a style resource describing the theme to use for the
187      *              window, or {@code 0} to use the default dialog theme
188      */
Dialog(@iContext @onNull Context context, @StyleRes int themeResId)189     public Dialog(@UiContext @NonNull Context context, @StyleRes int themeResId) {
190         this(context, themeResId, true);
191     }
192 
Dialog(@iContext @onNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper)193     Dialog(@UiContext @NonNull Context context, @StyleRes int themeResId,
194             boolean createContextThemeWrapper) {
195         if (createContextThemeWrapper) {
196             if (themeResId == Resources.ID_NULL) {
197                 final TypedValue outValue = new TypedValue();
198                 context.getTheme().resolveAttribute(R.attr.dialogTheme, outValue, true);
199                 themeResId = outValue.resourceId;
200             }
201             mContext = new ContextThemeWrapper(context, themeResId);
202         } else {
203             mContext = context;
204         }
205 
206         mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
207 
208         final Window w = new PhoneWindow(mContext);
209         mWindow = w;
210         w.setCallback(this);
211         w.setOnWindowDismissedCallback(this);
212         w.setOnWindowSwipeDismissedCallback(() -> {
213             if (mCancelable) {
214                 cancel();
215             }
216         });
217         w.setWindowManager(mWindowManager, null, null);
218         w.setGravity(Gravity.CENTER);
219 
220         mListenersHandler = new ListenersHandler(this);
221     }
222 
223     /**
224      * @deprecated
225      * @hide
226      */
227     @Deprecated
Dialog(@onNull Context context, boolean cancelable, @Nullable Message cancelCallback)228     protected Dialog(@NonNull Context context, boolean cancelable,
229             @Nullable Message cancelCallback) {
230         this(context);
231         mCancelable = cancelable;
232         mCancelMessage = cancelCallback;
233     }
234 
Dialog(@iContext @onNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener)235     protected Dialog(@UiContext @NonNull Context context, boolean cancelable,
236             @Nullable OnCancelListener cancelListener) {
237         this(context);
238         mCancelable = cancelable;
239         setOnCancelListener(cancelListener);
240     }
241 
242     /**
243      * Retrieve the Context this Dialog is running in.
244      *
245      * @return Context The Context used by the Dialog.
246      */
247     @UiContext
248     @NonNull
getContext()249     public final Context getContext() {
250         return mContext;
251     }
252 
253     /**
254      * Retrieve the {@link ActionBar} attached to this dialog, if present.
255      *
256      * @return The ActionBar attached to the dialog or null if no ActionBar is present.
257      */
getActionBar()258     public @Nullable ActionBar getActionBar() {
259         return mActionBar;
260     }
261 
262     /**
263      * Sets the Activity that owns this dialog. An example use: This Dialog will
264      * use the suggested volume control stream of the Activity.
265      *
266      * @param activity The Activity that owns this dialog.
267      */
setOwnerActivity(@onNull Activity activity)268     public final void setOwnerActivity(@NonNull Activity activity) {
269         mOwnerActivity = activity;
270 
271         getWindow().setVolumeControlStream(mOwnerActivity.getVolumeControlStream());
272     }
273 
274     /**
275      * Returns the Activity that owns this Dialog. For example, if
276      * {@link Activity#showDialog(int)} is used to show this Dialog, that
277      * Activity will be the owner (by default). Depending on how this dialog was
278      * created, this may return null.
279      *
280      * @return The Activity that owns this Dialog.
281      */
getOwnerActivity()282     public final @Nullable Activity getOwnerActivity() {
283         return mOwnerActivity;
284     }
285 
286     /**
287      * @return Whether the dialog is currently showing.
288      */
isShowing()289     public boolean isShowing() {
290         return mDecor == null ? false : mDecor.getVisibility() == View.VISIBLE;
291     }
292 
293     /**
294      * Forces immediate creation of the dialog.
295      * <p>
296      * Note that you should not override this method to perform dialog creation.
297      * Rather, override {@link #onCreate(Bundle)}.
298      */
create()299     public void create() {
300         if (!mCreated) {
301             dispatchOnCreate(null);
302         }
303     }
304 
305     /**
306      * Start the dialog and display it on screen.  The window is placed in the
307      * application layer and opaque.  Note that you should not override this
308      * method to do initialization when the dialog is shown, instead implement
309      * that in {@link #onStart}.
310      */
show()311     public void show() {
312         if (mShowing) {
313             if (mDecor != null) {
314                 if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
315                     mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
316                 }
317                 mDecor.setVisibility(View.VISIBLE);
318             }
319             return;
320         }
321 
322         mCanceled = false;
323 
324         if (!mCreated) {
325             dispatchOnCreate(null);
326         } else {
327             // Fill the DecorView in on any configuration changes that
328             // may have occured while it was removed from the WindowManager.
329             final Configuration config = mContext.getResources().getConfiguration();
330             mWindow.getDecorView().dispatchConfigurationChanged(config);
331         }
332 
333         onStart();
334         mDecor = mWindow.getDecorView();
335 
336         if (mActionBar == null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
337             final ApplicationInfo info = mContext.getApplicationInfo();
338             mWindow.setDefaultIcon(info.icon);
339             mWindow.setDefaultLogo(info.logo);
340             mActionBar = new WindowDecorActionBar(this);
341         }
342 
343         WindowManager.LayoutParams l = mWindow.getAttributes();
344         boolean restoreSoftInputMode = false;
345         if ((l.softInputMode
346                 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {
347             l.softInputMode |=
348                     WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
349             restoreSoftInputMode = true;
350         }
351 
352         mWindowManager.addView(mDecor, l);
353         if (restoreSoftInputMode) {
354             l.softInputMode &=
355                     ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
356         }
357 
358         mShowing = true;
359 
360         sendShowMessage();
361     }
362 
363     /**
364      * Hide the dialog, but do not dismiss it.
365      */
hide()366     public void hide() {
367         if (mDecor != null) {
368             mDecor.setVisibility(View.GONE);
369         }
370     }
371 
372     /**
373      * Dismiss this dialog, removing it from the screen. This method can be
374      * invoked safely from any thread.  Note that you should not override this
375      * method to do cleanup when the dialog is dismissed, instead implement
376      * that in {@link #onStop}.
377      */
378     @Override
dismiss()379     public void dismiss() {
380         if (mDismissOverride != null) {
381             mDismissOverride.run();
382             return;
383         }
384 
385         if (Looper.myLooper() == mHandler.getLooper()) {
386             dismissDialog();
387         } else {
388             mHandler.post(mDismissAction);
389         }
390     }
391 
392     @UnsupportedAppUsage
dismissDialog()393     void dismissDialog() {
394         if (mDecor == null || !mShowing) {
395             return;
396         }
397 
398         if (mWindow.isDestroyed()) {
399             Log.e(TAG, "Tried to dismissDialog() but the Dialog's window was already destroyed!");
400             return;
401         }
402 
403         try {
404             mWindowManager.removeViewImmediate(mDecor);
405         } finally {
406             if (mActionMode != null) {
407                 mActionMode.finish();
408             }
409             mDecor = null;
410             mWindow.closeAllPanels();
411             onStop();
412             mShowing = false;
413 
414             sendDismissMessage();
415         }
416     }
417 
sendDismissMessage()418     private void sendDismissMessage() {
419         if (mDismissMessage != null) {
420             // Obtain a new message so this dialog can be re-used
421             Message.obtain(mDismissMessage).sendToTarget();
422         }
423     }
424 
sendShowMessage()425     private void sendShowMessage() {
426         if (mShowMessage != null) {
427             // Obtain a new message so this dialog can be re-used
428             Message.obtain(mShowMessage).sendToTarget();
429         }
430     }
431 
432     // internal method to make sure mCreated is set properly without requiring
433     // users to call through to super in onCreate
dispatchOnCreate(Bundle savedInstanceState)434     void dispatchOnCreate(Bundle savedInstanceState) {
435         if (!mCreated) {
436             onCreate(savedInstanceState);
437             mCreated = true;
438         }
439     }
440 
441     /**
442      * Similar to {@link Activity#onCreate}, you should initialize your dialog
443      * in this method, including calling {@link #setContentView}.
444      * @param savedInstanceState If this dialog is being reinitialized after a
445      *     the hosting activity was previously shut down, holds the result from
446      *     the most recent call to {@link #onSaveInstanceState}, or null if this
447      *     is the first time.
448      */
onCreate(Bundle savedInstanceState)449     protected void onCreate(Bundle savedInstanceState) {
450     }
451 
452     /**
453      * Called when the dialog is starting.
454      */
onStart()455     protected void onStart() {
456         if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
457         if (allowsRegisterDefaultOnBackInvokedCallback() && mContext != null
458                 && WindowOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled(mContext)) {
459             // Add onBackPressed as default back behavior.
460             mDefaultBackCallback = this::onBackPressed;
461             getOnBackInvokedDispatcher().registerSystemOnBackInvokedCallback(mDefaultBackCallback);
462         }
463     }
464 
465     /**
466      * Called to tell you that you're stopping.
467      */
onStop()468     protected void onStop() {
469         if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
470         if (mDefaultBackCallback != null) {
471             getOnBackInvokedDispatcher().unregisterOnBackInvokedCallback(mDefaultBackCallback);
472             mDefaultBackCallback = null;
473         }
474     }
475 
476     /**
477      * Whether this dialog allows to register the default onBackInvokedCallback.
478      * @hide
479      */
allowsRegisterDefaultOnBackInvokedCallback()480     protected boolean allowsRegisterDefaultOnBackInvokedCallback() {
481         return true;
482     }
483 
484     private static final String DIALOG_SHOWING_TAG = "android:dialogShowing";
485     private static final String DIALOG_HIERARCHY_TAG = "android:dialogHierarchy";
486 
487     /**
488      * Saves the state of the dialog into a bundle.
489      *
490      * The default implementation saves the state of its view hierarchy, so you'll
491      * likely want to call through to super if you override this to save additional
492      * state.
493      * @return A bundle with the state of the dialog.
494      */
onSaveInstanceState()495     public @NonNull Bundle onSaveInstanceState() {
496         Bundle bundle = new Bundle();
497         bundle.putBoolean(DIALOG_SHOWING_TAG, mShowing);
498         if (mCreated) {
499             bundle.putBundle(DIALOG_HIERARCHY_TAG, mWindow.saveHierarchyState());
500         }
501         return bundle;
502     }
503 
504     /**
505      * Restore the state of the dialog from a previously saved bundle.
506      *
507      * The default implementation restores the state of the dialog's view
508      * hierarchy that was saved in the default implementation of {@link #onSaveInstanceState()},
509      * so be sure to call through to super when overriding unless you want to
510      * do all restoring of state yourself.
511      * @param savedInstanceState The state of the dialog previously saved by
512      *     {@link #onSaveInstanceState()}.
513      */
onRestoreInstanceState(@onNull Bundle savedInstanceState)514     public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
515         final Bundle dialogHierarchyState = savedInstanceState.getBundle(DIALOG_HIERARCHY_TAG);
516         if (dialogHierarchyState == null) {
517             // dialog has never been shown, or onCreated, nothing to restore.
518             return;
519         }
520         dispatchOnCreate(savedInstanceState);
521         mWindow.restoreHierarchyState(dialogHierarchyState);
522         if (savedInstanceState.getBoolean(DIALOG_SHOWING_TAG)) {
523             show();
524         }
525     }
526 
527     /**
528      * Retrieve the current Window for the activity.  This can be used to
529      * directly access parts of the Window API that are not available
530      * through Activity/Screen.
531      *
532      * @return Window The current window, or null if the activity is not
533      *         visual.
534      */
getWindow()535     public @Nullable Window getWindow() {
536         return mWindow;
537     }
538 
539     /**
540      * Call {@link android.view.Window#getCurrentFocus} on the
541      * Window if this Activity to return the currently focused view.
542      *
543      * @return View The current View with focus or null.
544      *
545      * @see #getWindow
546      * @see android.view.Window#getCurrentFocus
547      */
getCurrentFocus()548     public @Nullable View getCurrentFocus() {
549         return mWindow != null ? mWindow.getCurrentFocus() : null;
550     }
551 
552     /**
553      * Finds the first descendant view with the given ID or {@code null} if the
554      * ID is invalid (< 0), there is no matching view in the hierarchy, or the
555      * dialog has not yet been fully created (for example, via {@link #show()}
556      * or {@link #create()}).
557      * <p>
558      * <strong>Note:</strong> In most cases -- depending on compiler support --
559      * the resulting view is automatically cast to the target class type. If
560      * the target class type is unconstrained, an explicit cast may be
561      * necessary.
562      *
563      * @param id the ID to search for
564      * @return a view with given ID if found, or {@code null} otherwise
565      * @see View#findViewById(int)
566      * @see Dialog#requireViewById(int)
567      */
568     // Strictly speaking this should be marked as @Nullable but the nullability of the return value
569     // is deliberately left unspecified as idiomatically correct code can make assumptions either
570     // way based on local context, e.g. layout specification.
findViewById(@dRes int id)571     public <T extends View> T findViewById(@IdRes int id) {
572         return mWindow.findViewById(id);
573     }
574 
575     /**
576      * Finds the first descendant view with the given ID or throws an IllegalArgumentException if
577      * the ID is invalid (< 0), there is no matching view in the hierarchy, or the dialog has not
578      * yet been fully created (for example, via {@link #show()} or {@link #create()}).
579      * <p>
580      * <strong>Note:</strong> In most cases -- depending on compiler support --
581      * the resulting view is automatically cast to the target class type. If
582      * the target class type is unconstrained, an explicit cast may be
583      * necessary.
584      *
585      * @param id the ID to search for
586      * @return a view with given ID
587      * @see View#requireViewById(int)
588      * @see Dialog#findViewById(int)
589      */
590     @NonNull
requireViewById(@dRes int id)591     public final <T extends View> T requireViewById(@IdRes int id) {
592         T view = findViewById(id);
593         if (view == null) {
594             throw new IllegalArgumentException("ID does not reference a View inside this Dialog");
595         }
596         return view;
597     }
598 
599     /**
600      * Set the screen content from a layout resource.  The resource will be
601      * inflated, adding all top-level views to the screen.
602      *
603      * @param layoutResID Resource ID to be inflated.
604      */
setContentView(@ayoutRes int layoutResID)605     public void setContentView(@LayoutRes int layoutResID) {
606         mWindow.setContentView(layoutResID);
607     }
608 
609     /**
610      * Set the screen content to an explicit view.  This view is placed
611      * directly into the screen's view hierarchy.  It can itself be a complex
612      * view hierarchy.
613      *
614      * @param view The desired content to display.
615      */
setContentView(@onNull View view)616     public void setContentView(@NonNull View view) {
617         mWindow.setContentView(view);
618     }
619 
620     /**
621      * Set the screen content to an explicit view.  This view is placed
622      * directly into the screen's view hierarchy.  It can itself be a complex
623      * view hierarchy.
624      *
625      * @param view The desired content to display.
626      * @param params Layout parameters for the view.
627      */
setContentView(@onNull View view, @Nullable ViewGroup.LayoutParams params)628     public void setContentView(@NonNull View view, @Nullable ViewGroup.LayoutParams params) {
629         mWindow.setContentView(view, params);
630     }
631 
632     /**
633      * Add an additional content view to the screen.  Added after any existing
634      * ones in the screen -- existing views are NOT removed.
635      *
636      * @param view The desired content to display.
637      * @param params Layout parameters for the view.
638      */
addContentView(@onNull View view, @Nullable ViewGroup.LayoutParams params)639     public void addContentView(@NonNull View view, @Nullable ViewGroup.LayoutParams params) {
640         mWindow.addContentView(view, params);
641     }
642 
643     /**
644      * Set the title text for this dialog's window.
645      *
646      * @param title The new text to display in the title.
647      */
setTitle(@ullable CharSequence title)648     public void setTitle(@Nullable CharSequence title) {
649         mWindow.setTitle(title);
650         mWindow.getAttributes().setTitle(title);
651     }
652 
653     /**
654      * Set the title text for this dialog's window. The text is retrieved
655      * from the resources with the supplied identifier.
656      *
657      * @param titleId the title's text resource identifier
658      */
setTitle(@tringRes int titleId)659     public void setTitle(@StringRes int titleId) {
660         setTitle(mContext.getText(titleId));
661     }
662 
663     /**
664      * A key was pressed down.
665      * <p>
666      * If the focused view didn't want this event, this method is called.
667      * <p>
668      * Default implementation consumes {@link KeyEvent#KEYCODE_BACK KEYCODE_BACK}
669      * and, as of {@link android.os.Build.VERSION_CODES#P P}, {@link KeyEvent#KEYCODE_ESCAPE
670      * KEYCODE_ESCAPE} to later handle them in {@link #onKeyUp}.
671      *
672      * @see #onKeyUp
673      * @see android.view.KeyEvent
674      */
675     @Override
onKeyDown(int keyCode, @NonNull KeyEvent event)676     public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
677         if (keyCode == KeyEvent.KEYCODE_BACK) {
678             event.startTracking();
679             return true;
680         }
681         if (keyCode == KeyEvent.KEYCODE_ESCAPE) {
682             if (mCancelable) {
683                 cancel();
684                 event.startTracking();
685                 return true;
686             } else if (mWindow.shouldCloseOnTouchOutside()) {
687                 dismiss();
688                 event.startTracking();
689                 return true;
690             }
691         }
692 
693         return false;
694     }
695 
696     /**
697      * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
698      * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
699      * the event).
700      */
701     @Override
onKeyLongPress(int keyCode, @NonNull KeyEvent event)702     public boolean onKeyLongPress(int keyCode, @NonNull KeyEvent event) {
703         return false;
704     }
705 
706     /**
707      * A key was released.
708      * <p>
709      * Default implementation consumes {@link KeyEvent#KEYCODE_BACK KEYCODE_BACK}
710      * and, as of {@link android.os.Build.VERSION_CODES#P P}, {@link KeyEvent#KEYCODE_ESCAPE
711      * KEYCODE_ESCAPE} to close the dialog.
712      *
713      * @see #onKeyDown
714      * @see android.view.KeyEvent
715      */
716     @Override
onKeyUp(int keyCode, @NonNull KeyEvent event)717     public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
718         if (event.isTracking() && !event.isCanceled()) {
719             switch (keyCode) {
720                 case KeyEvent.KEYCODE_BACK:
721                     if (!WindowOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled(mContext)
722                             || !allowsRegisterDefaultOnBackInvokedCallback()) {
723                         onBackPressed();
724                         return true;
725                     }
726                     break;
727                 case KeyEvent.KEYCODE_ESCAPE:
728                     return true;
729             }
730         }
731         return false;
732     }
733 
734     /**
735      * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
736      * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
737      * the event).
738      */
739     @Override
onKeyMultiple(int keyCode, int repeatCount, @NonNull KeyEvent event)740     public boolean onKeyMultiple(int keyCode, int repeatCount, @NonNull KeyEvent event) {
741         return false;
742     }
743 
744     /**
745      * Called when the dialog has detected the user's press of the back
746      * key.  The default implementation simply cancels the dialog (only if
747      * it is cancelable), but you can override this to do whatever you want.
748      *
749      * <p>
750      * If you target version {@link android.os.Build.VERSION_CODES#TIRAMISU} or later, you
751      * should not use this method but register an {@link OnBackInvokedCallback} on an
752      * {@link OnBackInvokedDispatcher} that you can retrieve using
753      * {@link #getOnBackInvokedDispatcher()}. You should also set
754      * {@code android:enableOnBackInvokedCallback="true"} in the application manifest.
755      *
756      * <p>Alternatively, you
757      * can use {@code androidx.activity.ComponentDialog#getOnBackPressedDispatcher()}
758      * for backward compatibility.
759      *
760      * @deprecated Use {@link OnBackInvokedCallback} or
761      * {@code androidx.activity.OnBackPressedCallback} to handle back navigation instead.
762      * <p>
763      * Starting from Android 13 (API level 33), back event handling is
764      * moving to an ahead-of-time model and {@link #onBackPressed()} and
765      * {@link KeyEvent#KEYCODE_BACK} should not be used to handle back events (back gesture or
766      * back button click). Instead, an {@link OnBackInvokedCallback} should be registered using
767      * {@link Dialog#getOnBackInvokedDispatcher()}
768      * {@link OnBackInvokedDispatcher#registerOnBackInvokedCallback(int, OnBackInvokedCallback)
769      * .registerOnBackInvokedCallback(priority, callback)}.
770      */
771     @Deprecated
onBackPressed()772     public void onBackPressed() {
773         if (mCancelable) {
774             cancel();
775         }
776     }
777 
778     /**
779      * Called when a key shortcut event is not handled by any of the views in the Dialog.
780      * Override this method to implement global key shortcuts for the Dialog.
781      * Key shortcuts can also be implemented by setting the
782      * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
783      *
784      * @param keyCode The value in event.getKeyCode().
785      * @param event Description of the key event.
786      * @return True if the key shortcut was handled.
787      */
onKeyShortcut(int keyCode, @NonNull KeyEvent event)788     public boolean onKeyShortcut(int keyCode, @NonNull KeyEvent event) {
789         return false;
790     }
791 
792     /**
793      * Called when a touch screen event was not handled by any of the views
794      * under it. This is most useful to process touch events that happen outside
795      * of your window bounds, where there is no view to receive it.
796      *
797      * @param event The touch screen event being processed.
798      * @return Return true if you have consumed the event, false if you haven't.
799      *         The default implementation will cancel the dialog when a touch
800      *         happens outside of the window bounds.
801      */
onTouchEvent(@onNull MotionEvent event)802     public boolean onTouchEvent(@NonNull MotionEvent event) {
803         if (mCancelable && mShowing && mWindow.shouldCloseOnTouch(mContext, event)) {
804             cancel();
805             return true;
806         }
807 
808         return false;
809     }
810 
811     /**
812      * Called when the trackball was moved and not handled by any of the
813      * views inside of the activity.  So, for example, if the trackball moves
814      * while focus is on a button, you will receive a call here because
815      * buttons do not normally do anything with trackball events.  The call
816      * here happens <em>before</em> trackball movements are converted to
817      * DPAD key events, which then get sent back to the view hierarchy, and
818      * will be processed at the point for things like focus navigation.
819      *
820      * @param event The trackball event being processed.
821      *
822      * @return Return true if you have consumed the event, false if you haven't.
823      * The default implementation always returns false.
824      */
onTrackballEvent(@onNull MotionEvent event)825     public boolean onTrackballEvent(@NonNull MotionEvent event) {
826         return false;
827     }
828 
829     /**
830      * Called when a generic motion event was not handled by any of the
831      * views inside of the dialog.
832      * <p>
833      * Generic motion events describe joystick movements, mouse hovers, track pad
834      * touches, scroll wheel movements and other input events.  The
835      * {@link MotionEvent#getSource() source} of the motion event specifies
836      * the class of input that was received.  Implementations of this method
837      * must examine the bits in the source before processing the event.
838      * The following code example shows how this is done.
839      * </p><p>
840      * Generic motion events with source class
841      * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
842      * are delivered to the view under the pointer.  All other generic motion events are
843      * delivered to the focused view.
844      * </p><p>
845      * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
846      * handle this event.
847      * </p>
848      *
849      * @param event The generic motion event being processed.
850      *
851      * @return Return true if you have consumed the event, false if you haven't.
852      * The default implementation always returns false.
853      */
onGenericMotionEvent(@onNull MotionEvent event)854     public boolean onGenericMotionEvent(@NonNull MotionEvent event) {
855         return false;
856     }
857 
858     @Override
onWindowAttributesChanged(WindowManager.LayoutParams params)859     public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
860         if (mDecor != null) {
861             mWindowManager.updateViewLayout(mDecor, params);
862         }
863     }
864 
865     @Override
onContentChanged()866     public void onContentChanged() {
867     }
868 
869     @Override
onWindowFocusChanged(boolean hasFocus)870     public void onWindowFocusChanged(boolean hasFocus) {
871     }
872 
873     @Override
onAttachedToWindow()874     public void onAttachedToWindow() {
875     }
876 
877     @Override
onDetachedFromWindow()878     public void onDetachedFromWindow() {
879     }
880 
881     /** @hide */
882     @Override
onWindowDismissed(boolean finishTask, boolean suppressWindowTransition)883     public void onWindowDismissed(boolean finishTask, boolean suppressWindowTransition) {
884         dismiss();
885     }
886 
887     /**
888      * Called to process key events.  You can override this to intercept all
889      * key events before they are dispatched to the window.  Be sure to call
890      * this implementation for key events that should be handled normally.
891      *
892      * @param event The key event.
893      *
894      * @return boolean Return true if this event was consumed.
895      */
896     @Override
dispatchKeyEvent(@onNull KeyEvent event)897     public boolean dispatchKeyEvent(@NonNull KeyEvent event) {
898         if ((mOnKeyListener != null) && (mOnKeyListener.onKey(this, event.getKeyCode(), event))) {
899             return true;
900         }
901         if (mWindow.superDispatchKeyEvent(event)) {
902             return true;
903         }
904         return event.dispatch(this, mDecor != null
905                 ? mDecor.getKeyDispatcherState() : null, this);
906     }
907 
908     /**
909      * Called to process a key shortcut event.
910      * You can override this to intercept all key shortcut events before they are
911      * dispatched to the window.  Be sure to call this implementation for key shortcut
912      * events that should be handled normally.
913      *
914      * @param event The key shortcut event.
915      * @return True if this event was consumed.
916      */
917     @Override
dispatchKeyShortcutEvent(@onNull KeyEvent event)918     public boolean dispatchKeyShortcutEvent(@NonNull KeyEvent event) {
919         if (mWindow.superDispatchKeyShortcutEvent(event)) {
920             return true;
921         }
922         return onKeyShortcut(event.getKeyCode(), event);
923     }
924 
925     /**
926      * Called to process touch screen events.  You can override this to
927      * intercept all touch screen events before they are dispatched to the
928      * window.  Be sure to call this implementation for touch screen events
929      * that should be handled normally.
930      *
931      * @param ev The touch screen event.
932      *
933      * @return boolean Return true if this event was consumed.
934      */
935     @Override
dispatchTouchEvent(@onNull MotionEvent ev)936     public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
937         if (mWindow.superDispatchTouchEvent(ev)) {
938             return true;
939         }
940         return onTouchEvent(ev);
941     }
942 
943     /**
944      * Called to process trackball events.  You can override this to
945      * intercept all trackball events before they are dispatched to the
946      * window.  Be sure to call this implementation for trackball events
947      * that should be handled normally.
948      *
949      * @param ev The trackball event.
950      *
951      * @return boolean Return true if this event was consumed.
952      */
953     @Override
dispatchTrackballEvent(@onNull MotionEvent ev)954     public boolean dispatchTrackballEvent(@NonNull MotionEvent ev) {
955         if (mWindow.superDispatchTrackballEvent(ev)) {
956             return true;
957         }
958         return onTrackballEvent(ev);
959     }
960 
961     /**
962      * Called to process generic motion events.  You can override this to
963      * intercept all generic motion events before they are dispatched to the
964      * window.  Be sure to call this implementation for generic motion events
965      * that should be handled normally.
966      *
967      * @param ev The generic motion event.
968      *
969      * @return boolean Return true if this event was consumed.
970      */
971     @Override
dispatchGenericMotionEvent(@onNull MotionEvent ev)972     public boolean dispatchGenericMotionEvent(@NonNull MotionEvent ev) {
973         if (mWindow.superDispatchGenericMotionEvent(ev)) {
974             return true;
975         }
976         return onGenericMotionEvent(ev);
977     }
978 
979     @Override
dispatchPopulateAccessibilityEvent(@onNull AccessibilityEvent event)980     public boolean dispatchPopulateAccessibilityEvent(@NonNull AccessibilityEvent event) {
981         event.setClassName(getClass().getName());
982         event.setPackageName(mContext.getPackageName());
983 
984         LayoutParams params = getWindow().getAttributes();
985         boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
986             (params.height == LayoutParams.MATCH_PARENT);
987         event.setFullScreen(isFullScreen);
988 
989         return false;
990     }
991 
992     /**
993      * @see Activity#onCreatePanelView(int)
994      */
995     @Override
onCreatePanelView(int featureId)996     public View onCreatePanelView(int featureId) {
997         return null;
998     }
999 
1000     /**
1001      * @see Activity#onCreatePanelMenu(int, Menu)
1002      */
1003     @Override
onCreatePanelMenu(int featureId, @NonNull Menu menu)1004     public boolean onCreatePanelMenu(int featureId, @NonNull Menu menu) {
1005         if (featureId == Window.FEATURE_OPTIONS_PANEL) {
1006             return onCreateOptionsMenu(menu);
1007         }
1008 
1009         return false;
1010     }
1011 
1012     /**
1013      * @see Activity#onPreparePanel(int, View, Menu)
1014      */
1015     @Override
onPreparePanel(int featureId, @Nullable View view, @NonNull Menu menu)1016     public boolean onPreparePanel(int featureId, @Nullable View view, @NonNull Menu menu) {
1017         if (featureId == Window.FEATURE_OPTIONS_PANEL) {
1018             return onPrepareOptionsMenu(menu) && menu.hasVisibleItems();
1019         }
1020         return true;
1021     }
1022 
1023     /**
1024      * @see Activity#onMenuOpened(int, Menu)
1025      */
1026     @Override
onMenuOpened(int featureId, @NonNull Menu menu)1027     public boolean onMenuOpened(int featureId, @NonNull Menu menu) {
1028         if (featureId == Window.FEATURE_ACTION_BAR) {
1029             mActionBar.dispatchMenuVisibilityChanged(true);
1030         }
1031         return true;
1032     }
1033 
1034     /**
1035      * @see Activity#onMenuItemSelected(int, MenuItem)
1036      */
1037     @Override
onMenuItemSelected(int featureId, @NonNull MenuItem item)1038     public boolean onMenuItemSelected(int featureId, @NonNull MenuItem item) {
1039         return false;
1040     }
1041 
1042     /**
1043      * @see Activity#onPanelClosed(int, Menu)
1044      */
1045     @Override
onPanelClosed(int featureId, @NonNull Menu menu)1046     public void onPanelClosed(int featureId, @NonNull Menu menu) {
1047         if (featureId == Window.FEATURE_ACTION_BAR) {
1048             mActionBar.dispatchMenuVisibilityChanged(false);
1049         }
1050     }
1051 
1052     /**
1053      * It is usually safe to proxy this call to the owner activity's
1054      * {@link Activity#onCreateOptionsMenu(Menu)} if the client desires the same
1055      * menu for this Dialog.
1056      *
1057      * @see Activity#onCreateOptionsMenu(Menu)
1058      * @see #getOwnerActivity()
1059      */
onCreateOptionsMenu(@onNull Menu menu)1060     public boolean onCreateOptionsMenu(@NonNull Menu menu) {
1061         return true;
1062     }
1063 
1064     /**
1065      * It is usually safe to proxy this call to the owner activity's
1066      * {@link Activity#onPrepareOptionsMenu(Menu)} if the client desires the
1067      * same menu for this Dialog.
1068      *
1069      * @see Activity#onPrepareOptionsMenu(Menu)
1070      * @see #getOwnerActivity()
1071      */
onPrepareOptionsMenu(@onNull Menu menu)1072     public boolean onPrepareOptionsMenu(@NonNull Menu menu) {
1073         return true;
1074     }
1075 
1076     /**
1077      * @see Activity#onOptionsItemSelected(MenuItem)
1078      */
onOptionsItemSelected(@onNull MenuItem item)1079     public boolean onOptionsItemSelected(@NonNull MenuItem item) {
1080         return false;
1081     }
1082 
1083     /**
1084      * @see Activity#onOptionsMenuClosed(Menu)
1085      */
onOptionsMenuClosed(@onNull Menu menu)1086     public void onOptionsMenuClosed(@NonNull Menu menu) {
1087     }
1088 
1089     /**
1090      * @see Activity#openOptionsMenu()
1091      */
openOptionsMenu()1092     public void openOptionsMenu() {
1093         if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
1094             mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
1095         }
1096     }
1097 
1098     /**
1099      * @see Activity#closeOptionsMenu()
1100      */
closeOptionsMenu()1101     public void closeOptionsMenu() {
1102         if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
1103             mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
1104         }
1105     }
1106 
1107     /**
1108      * @see Activity#invalidateOptionsMenu()
1109      */
invalidateOptionsMenu()1110     public void invalidateOptionsMenu() {
1111         if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
1112             mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
1113         }
1114     }
1115 
1116     /**
1117      * @see Activity#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)
1118      */
1119     @Override
onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)1120     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1121     }
1122 
1123     /**
1124      * @see Activity#registerForContextMenu(View)
1125      */
registerForContextMenu(@onNull View view)1126     public void registerForContextMenu(@NonNull View view) {
1127         view.setOnCreateContextMenuListener(this);
1128     }
1129 
1130     /**
1131      * @see Activity#unregisterForContextMenu(View)
1132      */
unregisterForContextMenu(@onNull View view)1133     public void unregisterForContextMenu(@NonNull View view) {
1134         view.setOnCreateContextMenuListener(null);
1135     }
1136 
1137     /**
1138      * @see Activity#openContextMenu(View)
1139      */
openContextMenu(@onNull View view)1140     public void openContextMenu(@NonNull View view) {
1141         view.showContextMenu();
1142     }
1143 
1144     /**
1145      * @see Activity#onContextItemSelected(MenuItem)
1146      */
onContextItemSelected(@onNull MenuItem item)1147     public boolean onContextItemSelected(@NonNull MenuItem item) {
1148         return false;
1149     }
1150 
1151     /**
1152      * @see Activity#onContextMenuClosed(Menu)
1153      */
onContextMenuClosed(@onNull Menu menu)1154     public void onContextMenuClosed(@NonNull Menu menu) {
1155     }
1156 
1157     /**
1158      * This hook is called when the user signals the desire to start a search.
1159      */
1160     @Override
onSearchRequested(@onNull SearchEvent searchEvent)1161     public boolean onSearchRequested(@NonNull SearchEvent searchEvent) {
1162         mSearchEvent = searchEvent;
1163         return onSearchRequested();
1164     }
1165 
1166     /**
1167      * This hook is called when the user signals the desire to start a search.
1168      */
1169     @Override
onSearchRequested()1170     public boolean onSearchRequested() {
1171         final SearchManager searchManager = (SearchManager) mContext
1172                 .getSystemService(Context.SEARCH_SERVICE);
1173 
1174         // associate search with owner activity
1175         final ComponentName appName = getAssociatedActivity();
1176         if (appName != null && searchManager.getSearchableInfo(appName) != null) {
1177             searchManager.startSearch(null, false, appName, null, false);
1178             dismiss();
1179             return true;
1180         } else {
1181             return false;
1182         }
1183     }
1184 
1185     /**
1186      * During the onSearchRequested() callbacks, this function will return the
1187      * {@link SearchEvent} that triggered the callback, if it exists.
1188      *
1189      * @return SearchEvent The SearchEvent that triggered the {@link
1190      *                    #onSearchRequested} callback.
1191      */
getSearchEvent()1192     public final @Nullable SearchEvent getSearchEvent() {
1193         return mSearchEvent;
1194     }
1195 
1196     @Override
onWindowStartingActionMode(ActionMode.Callback callback)1197     public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
1198         if (mActionBar != null && mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
1199             return mActionBar.startActionMode(callback);
1200         }
1201         return null;
1202     }
1203 
1204     @Override
onWindowStartingActionMode(ActionMode.Callback callback, int type)1205     public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
1206         try {
1207             mActionModeTypeStarting = type;
1208             return onWindowStartingActionMode(callback);
1209         } finally {
1210             mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
1211         }
1212     }
1213 
1214     /**
1215      * {@inheritDoc}
1216      *
1217      * Note that if you override this method you should always call through
1218      * to the superclass implementation by calling super.onActionModeStarted(mode).
1219      */
1220     @Override
1221     @CallSuper
onActionModeStarted(ActionMode mode)1222     public void onActionModeStarted(ActionMode mode) {
1223         mActionMode = mode;
1224     }
1225 
1226     /**
1227      * {@inheritDoc}
1228      *
1229      * Note that if you override this method you should always call through
1230      * to the superclass implementation by calling super.onActionModeFinished(mode).
1231      */
1232     @Override
1233     @CallSuper
onActionModeFinished(ActionMode mode)1234     public void onActionModeFinished(ActionMode mode) {
1235         if (mode == mActionMode) {
1236             mActionMode = null;
1237         }
1238     }
1239 
1240     /**
1241      * @return The activity associated with this dialog, or null if there is no associated activity.
1242      */
getAssociatedActivity()1243     private ComponentName getAssociatedActivity() {
1244         Activity activity = mOwnerActivity;
1245         Context context = getContext();
1246         while (activity == null && context != null) {
1247             if (context instanceof Activity) {
1248                 activity = (Activity) context;  // found it!
1249             } else {
1250                 context = (context instanceof ContextWrapper) ?
1251                         ((ContextWrapper) context).getBaseContext() : // unwrap one level
1252                         null;                                         // done
1253             }
1254         }
1255         return activity == null ? null : activity.getComponentName();
1256     }
1257 
1258 
1259     /**
1260      * Request that key events come to this dialog. Use this if your
1261      * dialog has no views with focus, but the dialog still wants
1262      * a chance to process key events.
1263      *
1264      * @param get true if the dialog should receive key events, false otherwise
1265      * @see android.view.Window#takeKeyEvents
1266      */
takeKeyEvents(boolean get)1267     public void takeKeyEvents(boolean get) {
1268         mWindow.takeKeyEvents(get);
1269     }
1270 
1271     /**
1272      * Enable extended window features.  This is a convenience for calling
1273      * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
1274      *
1275      * @param featureId The desired feature as defined in
1276      *                  {@link android.view.Window}.
1277      * @return Returns true if the requested feature is supported and now
1278      *         enabled.
1279      *
1280      * @see android.view.Window#requestFeature
1281      */
requestWindowFeature(int featureId)1282     public final boolean requestWindowFeature(int featureId) {
1283         return getWindow().requestFeature(featureId);
1284     }
1285 
1286     /**
1287      * Convenience for calling
1288      * {@link android.view.Window#setFeatureDrawableResource}.
1289      */
setFeatureDrawableResource(int featureId, @DrawableRes int resId)1290     public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
1291         getWindow().setFeatureDrawableResource(featureId, resId);
1292     }
1293 
1294     /**
1295      * Convenience for calling
1296      * {@link android.view.Window#setFeatureDrawableUri}.
1297      */
setFeatureDrawableUri(int featureId, @Nullable Uri uri)1298     public final void setFeatureDrawableUri(int featureId, @Nullable Uri uri) {
1299         getWindow().setFeatureDrawableUri(featureId, uri);
1300     }
1301 
1302     /**
1303      * Convenience for calling
1304      * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
1305      */
setFeatureDrawable(int featureId, @Nullable Drawable drawable)1306     public final void setFeatureDrawable(int featureId, @Nullable Drawable drawable) {
1307         getWindow().setFeatureDrawable(featureId, drawable);
1308     }
1309 
1310     /**
1311      * Convenience for calling
1312      * {@link android.view.Window#setFeatureDrawableAlpha}.
1313      */
setFeatureDrawableAlpha(int featureId, int alpha)1314     public final void setFeatureDrawableAlpha(int featureId, int alpha) {
1315         getWindow().setFeatureDrawableAlpha(featureId, alpha);
1316     }
1317 
getLayoutInflater()1318     public @NonNull LayoutInflater getLayoutInflater() {
1319         return getWindow().getLayoutInflater();
1320     }
1321 
1322     /**
1323      * Sets whether this dialog is cancelable with the
1324      * {@link KeyEvent#KEYCODE_BACK BACK} key.
1325      */
setCancelable(boolean flag)1326     public void setCancelable(boolean flag) {
1327         mCancelable = flag;
1328     }
1329 
1330     /**
1331      * Sets whether this dialog is canceled when touched outside the window's
1332      * bounds. If setting to true, the dialog is set to be cancelable if not
1333      * already set.
1334      *
1335      * @param cancel Whether the dialog should be canceled when touched outside
1336      *            the window.
1337      */
setCanceledOnTouchOutside(boolean cancel)1338     public void setCanceledOnTouchOutside(boolean cancel) {
1339         if (cancel && !mCancelable) {
1340             mCancelable = true;
1341         }
1342 
1343         mWindow.setCloseOnTouchOutside(cancel);
1344     }
1345 
1346     /**
1347      * Cancel the dialog.  This is essentially the same as calling {@link #dismiss()}, but it will
1348      * also call your {@link DialogInterface.OnCancelListener} (if registered).
1349      */
1350     @Override
cancel()1351     public void cancel() {
1352         if (!mCanceled && mCancelMessage != null) {
1353             mCanceled = true;
1354             // Obtain a new message so this dialog can be re-used
1355             Message.obtain(mCancelMessage).sendToTarget();
1356         }
1357         dismiss();
1358     }
1359 
1360     /**
1361      * Set a listener to be invoked when the dialog is canceled.
1362      *
1363      * <p>This will only be invoked when the dialog is canceled.
1364      * Cancel events alone will not capture all ways that
1365      * the dialog might be dismissed. If the creator needs
1366      * to know when a dialog is dismissed in general, use
1367      * {@link #setOnDismissListener}.</p>
1368      *
1369      * @param listener The {@link DialogInterface.OnCancelListener} to use.
1370      */
setOnCancelListener(@ullable OnCancelListener listener)1371     public void setOnCancelListener(@Nullable OnCancelListener listener) {
1372         if (mCancelAndDismissTaken != null) {
1373             throw new IllegalStateException(
1374                     "OnCancelListener is already taken by "
1375                     + mCancelAndDismissTaken + " and can not be replaced.");
1376         }
1377         if (listener != null) {
1378             mCancelMessage = mListenersHandler.obtainMessage(CANCEL, listener);
1379         } else {
1380             mCancelMessage = null;
1381         }
1382     }
1383 
1384     /**
1385      * Set a message to be sent when the dialog is canceled.
1386      * @param msg The msg to send when the dialog is canceled.
1387      * @see #setOnCancelListener(android.content.DialogInterface.OnCancelListener)
1388      */
setCancelMessage(@ullable Message msg)1389     public void setCancelMessage(@Nullable Message msg) {
1390         mCancelMessage = msg;
1391     }
1392 
1393     /**
1394      * Set a listener to be invoked when the dialog is dismissed.
1395      * @param listener The {@link DialogInterface.OnDismissListener} to use.
1396      */
setOnDismissListener(@ullable OnDismissListener listener)1397     public void setOnDismissListener(@Nullable OnDismissListener listener) {
1398         if (mCancelAndDismissTaken != null) {
1399             throw new IllegalStateException(
1400                     "OnDismissListener is already taken by "
1401                     + mCancelAndDismissTaken + " and can not be replaced.");
1402         }
1403         if (listener != null) {
1404             mDismissMessage = mListenersHandler.obtainMessage(DISMISS, listener);
1405         } else {
1406             mDismissMessage = null;
1407         }
1408     }
1409 
1410     /**
1411      * Sets a listener to be invoked when the dialog is shown.
1412      * @param listener The {@link DialogInterface.OnShowListener} to use.
1413      */
setOnShowListener(@ullable OnShowListener listener)1414     public void setOnShowListener(@Nullable OnShowListener listener) {
1415         if (listener != null) {
1416             mShowMessage = mListenersHandler.obtainMessage(SHOW, listener);
1417         } else {
1418             mShowMessage = null;
1419         }
1420     }
1421 
1422     /**
1423      * Set a message to be sent when the dialog is dismissed.
1424      * @param msg The msg to send when the dialog is dismissed.
1425      */
setDismissMessage(@ullable Message msg)1426     public void setDismissMessage(@Nullable Message msg) {
1427         mDismissMessage = msg;
1428     }
1429 
1430     /**
1431      * Set a {@link Runnable} to run when this dialog is dismissed instead of directly dismissing
1432      * it. This allows to animate the dialog in its window before dismissing it.
1433      *
1434      * Note that {@code override} should always end up calling this method with {@code null}
1435      * followed by a call to {@link #dismiss() dismiss} to actually dismiss the dialog.
1436      *
1437      * @see #dismiss()
1438      *
1439      * @hide
1440      */
setDismissOverride(@ullable Runnable override)1441     public void setDismissOverride(@Nullable Runnable override) {
1442         mDismissOverride = override;
1443     }
1444 
1445     /** @hide */
takeCancelAndDismissListeners(@ullable String msg, @Nullable OnCancelListener cancel, @Nullable OnDismissListener dismiss)1446     public boolean takeCancelAndDismissListeners(@Nullable String msg,
1447             @Nullable OnCancelListener cancel, @Nullable OnDismissListener dismiss) {
1448         if (mCancelAndDismissTaken != null) {
1449             mCancelAndDismissTaken = null;
1450         } else if (mCancelMessage != null || mDismissMessage != null) {
1451             return false;
1452         }
1453 
1454         setOnCancelListener(cancel);
1455         setOnDismissListener(dismiss);
1456         mCancelAndDismissTaken = msg;
1457 
1458         return true;
1459     }
1460 
1461     /**
1462      * By default, this will use the owner Activity's suggested stream type.
1463      *
1464      * @see Activity#setVolumeControlStream(int)
1465      * @see #setOwnerActivity(Activity)
1466      */
setVolumeControlStream(int streamType)1467     public final void setVolumeControlStream(int streamType) {
1468         getWindow().setVolumeControlStream(streamType);
1469     }
1470 
1471     /**
1472      * @see Activity#getVolumeControlStream()
1473      */
getVolumeControlStream()1474     public final int getVolumeControlStream() {
1475         return getWindow().getVolumeControlStream();
1476     }
1477 
1478     /**
1479      * Sets the callback that will be called if a key is dispatched to the dialog.
1480      */
setOnKeyListener(@ullable OnKeyListener onKeyListener)1481     public void setOnKeyListener(@Nullable OnKeyListener onKeyListener) {
1482         mOnKeyListener = onKeyListener;
1483     }
1484 
1485     private static final class ListenersHandler extends Handler {
1486         private final WeakReference<DialogInterface> mDialog;
1487 
ListenersHandler(Dialog dialog)1488         public ListenersHandler(Dialog dialog) {
1489             mDialog = new WeakReference<>(dialog);
1490         }
1491 
1492         @Override
handleMessage(Message msg)1493         public void handleMessage(Message msg) {
1494             switch (msg.what) {
1495                 case DISMISS:
1496                     ((OnDismissListener) msg.obj).onDismiss(mDialog.get());
1497                     break;
1498                 case CANCEL:
1499                     ((OnCancelListener) msg.obj).onCancel(mDialog.get());
1500                     break;
1501                 case SHOW:
1502                     ((OnShowListener) msg.obj).onShow(mDialog.get());
1503                     break;
1504             }
1505         }
1506     }
1507 
1508     /**
1509      * Returns the {@link OnBackInvokedDispatcher} instance associated with the window that this
1510      * dialog is attached to.
1511      */
1512     @NonNull
getOnBackInvokedDispatcher()1513     public OnBackInvokedDispatcher getOnBackInvokedDispatcher() {
1514         return mWindow.getOnBackInvokedDispatcher();
1515     }
1516 }
1517