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