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