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