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