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