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