Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2006 The Android Open Source Project
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
    *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package android.app;
  
  
  import android.net.Uri;
  import android.os.Bundle;
  import android.view.Menu;
  import android.view.View;
  
Base class for Dialogs.

Note: Activities provide a facility to manage the creation, saving and restoring of dialogs. See Activity.onCreateDialog(int), Activity.onPrepareDialog(int,android.app.Dialog), Activity.showDialog(int), and Activity.dismissDialog(int). If these methods are used, getOwnerActivity() will return the Activity that managed this dialog.

Often you will want to have a Dialog display on top of the current input method, because there is no reason for it to accept text. You can do this by setting the WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM window flag (assuming your Dialog takes input focus, as it the default) with the following code:

     getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
             WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
 
  
  public class Dialog implements DialogInterfaceWindow.Callback,
      private Activity mOwnerActivity;
      
      final Context mContext;
      final WindowManager mWindowManager;
      Window mWindow;
      View mDecor;
    
This field should be made private, so it is hidden from the SDK.
  
      protected boolean mCancelable = true;
  
      private Message mCancelMessage;
      private Message mDismissMessage;
      private Message mShowMessage;

    
Whether to cancel the dialog when a touch is received outside of the window's bounds.
  
      private boolean mCanceledOnTouchOutside = false;
      
      private OnKeyListener mOnKeyListener;
  
      private boolean mCreated = false;
      private boolean mShowing = false;
  
     private final Thread mUiThread;
     private final Handler mHandler = new Handler();
 
     private static final int DISMISS = 0x43;
     private static final int CANCEL = 0x44;
     private static final int SHOW = 0x45;
 
     private Handler mListenersHandler;
 
     private final Runnable mDismissAction = new Runnable() {
         public void run() {
             dismissDialog();
         }
     };

    
Create a Dialog window that uses the default dialog frame style.

Parameters:
context The Context the Dialog is to run it. In particular, it uses the window manager and theme in this context to present its UI.
 
     public Dialog(Context context) {
         this(context, 0);
     }

    
Create a Dialog window that uses a custom dialog style.

Parameters:
context The Context in which the Dialog should run. In particular, it uses the window manager and theme from this context to present its UI.
theme A style resource describing the theme to use for the window. See Style and Theme Resources for more information about defining and using styles. This theme is applied on top of the current theme in context. If 0, the default dialog theme will be used.
 
     public Dialog(Context contextint theme) {
          = new ContextThemeWrapper(
             contexttheme == 0 ? ..... : theme);
          = (WindowManager)context.getSystemService("window");
         Window w = PolicyManager.makeNewWindow();
          = w;
         w.setCallback(this);
         w.setWindowManager(nullnull);
         w.setGravity(.);
          = Thread.currentThread();
          = new ListenersHandler(this);
     }

    

Deprecated:
Hide:
 
     @Deprecated
     protected Dialog(Context contextboolean cancelable,
             Message cancelCallback) {
         this(context);
          = cancelable;
          = cancelCallback;
     }
 
     protected Dialog(Context contextboolean cancelable,
             OnCancelListener cancelListener) {
         this(context);
          = cancelable;
         setOnCancelListener(cancelListener);
     }

    
Retrieve the Context this Dialog is running in.

Returns:
Context The Context that was supplied to the constructor.
 
     public final Context getContext() {
         return ;
     }

    
Sets the Activity that owns this dialog. An example use: This Dialog will use the suggested volume control stream of the Activity.

Parameters:
activity The Activity that owns this dialog.
 
     public final void setOwnerActivity(Activity activity) {
          = activity;
         
     }

    
Returns the Activity that owns this Dialog. For example, if Activity.showDialog(int) is used to show this Dialog, that Activity will be the owner (by default). Depending on how this dialog was created, this may return null.

Returns:
The Activity that owns this Dialog.
 
     public final Activity getOwnerActivity() {
         return ;
     }
    
    

Returns:
Whether the dialog is currently showing.
 
     public boolean isShowing() {
         return ;
     }

    
Start the dialog and display it on screen. The window is placed in the application layer and opaque. Note that you should not override this method to do initialization when the dialog is shown, instead implement that in onStart().
 
     public void show() {
         if () {
             if ( != null) {
                 .setVisibility(.);
             }
             return;
         }
 
         if (!) {
             dispatchOnCreate(null);
         }
 
         onStart();
          = .getDecorView();
         if ((l.softInputMode
                 & ..) == 0) {
             WindowManager.LayoutParams nl = new WindowManager.LayoutParams();
             nl.copyFrom(l);
             nl.softInputMode |=
                     ..;
             l = nl;
         }
 
         try {
             .addView(l);
              = true;
     
             sendShowMessage();
         } finally {
         }
     }
    
    
Hide the dialog, but do not dismiss it.
 
     public void hide() {
         if ( != null) {
             .setVisibility(.);
         }
     }

    
Dismiss this dialog, removing it from the screen. This method can be invoked safely from any thread. Note that you should not override this method to do cleanup when the dialog is dismissed, instead implement that in onStop().
 
     public void dismiss() {
         if (Thread.currentThread() != ) {
             .post();
         } else {
             .run();
         }
     }
 
     private void dismissDialog() {
         if ( == null || !) {
             return;
         }
 
         try {
             .removeView();
         } finally {
              = null;
             .closeAllPanels();
             onStop();
              = false;
             
             sendDismissMessage();
         }
     }
 
     private void sendDismissMessage() {
         if ( != null) {
             // Obtain a new message so this dialog can be re-used
             Message.obtain().sendToTarget();
         }
     }
 
     private void sendShowMessage() {
         if ( != null) {
             // Obtain a new message so this dialog can be re-used
             Message.obtain().sendToTarget();
         }
     }
 
     // internal method to make sure mcreated is set properly without requiring
     // users to call through to super in onCreate
     void dispatchOnCreate(Bundle savedInstanceState) {
         if (!) {
             onCreate(savedInstanceState);
              = true;
         }
     }

    
Similar to Activity.onCreate(android.os.Bundle), you should initialized your dialog in this method, including calling setContentView(int).

Parameters:
savedInstanceState If this dialog is being reinitalized after a the hosting activity was previously shut down, holds the result from the most recent call to onSaveInstanceState(), or null if this is the first time.
 
     protected void onCreate(Bundle savedInstanceState) {
     }

    
Called when the dialog is starting.
 
     protected void onStart() {
     }

    
Called to tell you that you're stopping.
 
     protected void onStop() {
     }
 
     private static final String DIALOG_SHOWING_TAG = "android:dialogShowing";
     private static final String DIALOG_HIERARCHY_TAG = "android:dialogHierarchy";

    
Saves the state of the dialog into a bundle. The default implementation saves the state of its view hierarchy, so you'll likely want to call through to super if you override this to save additional state.

Returns:
A bundle with the state of the dialog.
 
     public Bundle onSaveInstanceState() {
         Bundle bundle = new Bundle();
         bundle.putBoolean();
         if () {
             bundle.putBundle(.saveHierarchyState());
         }
         return bundle;
     }

    
Restore the state of the dialog from a previously saved bundle. The default implementation restores the state of the dialog's view hierarchy that was saved in the default implementation of onSaveInstanceState(), so be sure to call through to super when overriding unless you want to do all restoring of state yourself.

Parameters:
savedInstanceState The state of the dialog previously saved by onSaveInstanceState().
 
     public void onRestoreInstanceState(Bundle savedInstanceState) {
         final Bundle dialogHierarchyState = savedInstanceState.getBundle();
         if (dialogHierarchyState == null) {
             // dialog has never been shown, or onCreated, nothing to restore.
             return;
         }
         dispatchOnCreate(savedInstanceState);
         .restoreHierarchyState(dialogHierarchyState);
         if (savedInstanceState.getBoolean()) {
             show();
         }
     }

    
Retrieve the current Window for the activity. This can be used to directly access parts of the Window API that are not available through Activity/Screen.

Returns:
Window The current window, or null if the activity is not visual.
 
     public Window getWindow() {
         return ;
     }

    
Call android.view.Window.getCurrentFocus() on the Window if this Activity to return the currently focused view.

Returns:
View The current View with focus or null.
See also:
getWindow()
android.view.Window.getCurrentFocus()
 
     public View getCurrentFocus() {
         return  != null ? .getCurrentFocus() : null;
     }

    
Finds a view that was identified by the id attribute from the XML that was processed in onStart().

Parameters:
id the identifier of the view to find
Returns:
The view if found or null otherwise.
 
     public View findViewById(int id) {
         return .findViewById(id);
     }

    
Set the screen content from a layout resource. The resource will be inflated, adding all top-level views to the screen.

Parameters:
layoutResID Resource ID to be inflated.
 
     public void setContentView(int layoutResID) {
         .setContentView(layoutResID);
     }

    
Set the screen content to an explicit view. This view is placed directly into the screen's view hierarchy. It can itself be a complex view hierarhcy.

Parameters:
view The desired content to display.
 
     public void setContentView(View view) {
         .setContentView(view);
     }

    
Set the screen content to an explicit view. This view is placed directly into the screen's view hierarchy. It can itself be a complex view hierarhcy.

Parameters:
view The desired content to display.
params Layout parameters for the view.
 
     public void setContentView(View viewViewGroup.LayoutParams params) {
         .setContentView(viewparams);
     }

    
Add an additional content view to the screen. Added after any existing ones in the screen -- existing views are NOT removed.

Parameters:
view The desired content to display.
params Layout parameters for the view.
 
     public void addContentView(View viewViewGroup.LayoutParams params) {
         .addContentView(viewparams);
     }

    
Set the title text for this dialog's window.

Parameters:
title The new text to display in the title.
 
     public void setTitle(CharSequence title) {
         .setTitle(title);
         .getAttributes().setTitle(title);
     }

    
Set the title text for this dialog's window. The text is retrieved from the resources with the supplied identifier.

Parameters:
titleId the title's text resource identifier
 
     public void setTitle(int titleId) {
         setTitle(.getText(titleId));
     }

    
A key was pressed down.

If the focused view didn't want this event, this method is called.

The default implementation consumed the KEYCODE_BACK to later handle it in onKeyUp(int,android.view.KeyEvent).

 
     public boolean onKeyDown(int keyCodeKeyEvent event) {
         if (keyCode == .) {
             event.startTracking();
             return true;
         }
 
         return false;
     }

    
Default implementation of KeyEvent.Callback.onKeyLongPress(): always returns false (doesn't handle the event).
 
     public boolean onKeyLongPress(int keyCodeKeyEvent event) {
         return false;
     }

    
A key was released.

The default implementation handles KEYCODE_BACK to close the dialog.

 
     public boolean onKeyUp(int keyCodeKeyEvent event) {
         if (keyCode == . && event.isTracking()
                 && !event.isCanceled()) {
             onBackPressed();
             return true;
         }
         return false;
     }

    
Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).
 
     public boolean onKeyMultiple(int keyCodeint repeatCountKeyEvent event) {
         return false;
     }
    
    
Called when the dialog has detected the user's press of the back key. The default implementation simply cancels the dialog (only if it is cancelable), but you can override this to do whatever you want.
 
     public void onBackPressed() {
         if () {
             cancel();
         }
     }
    
    
Called when a touch screen event was not handled by any of the views under it. This is most useful to process touch events that happen outside of your window bounds, where there is no view to receive it.

Parameters:
event The touch screen event being processed.
Returns:
Return true if you have consumed the event, false if you haven't. The default implementation will cancel the dialog when a touch happens outside of the window bounds.
 
     public boolean onTouchEvent(MotionEvent event) {
         if ( &&  && event.getAction() == .
                 && isOutOfBounds(event)) {
             cancel();
             return true;
         }
         
         return false;
     }
 
     private boolean isOutOfBounds(MotionEvent event) {
         final int x = (intevent.getX();
         final int y = (intevent.getY();
         final int slop = ViewConfiguration.get().getScaledWindowTouchSlop();
         final View decorView = getWindow().getDecorView();
         return (x < -slop) || (y < -slop)
                 || (x > (decorView.getWidth()+slop))
                 || (y > (decorView.getHeight()+slop));
     }
    
    
Called when the trackball was moved and not handled by any of the views inside of the activity. So, for example, if the trackball moves while focus is on a button, you will receive a call here because buttons do not normally do anything with trackball events. The call here happens before trackball movements are converted to DPAD key events, which then get sent back to the view hierarchy, and will be processed at the point for things like focus navigation.

Parameters:
event The trackball event being processed.
Returns:
Return true if you have consumed the event, false if you haven't. The default implementation always returns false.
 
     public boolean onTrackballEvent(MotionEvent event) {
         return false;
     }
     
     public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
         if ( != null) {
             .updateViewLayout(params);
         }
     }
 
     public void onContentChanged() {
     }
     
     public void onWindowFocusChanged(boolean hasFocus) {
     }
 
     public void onAttachedToWindow() {
     }
     
     public void onDetachedFromWindow() {
     }
    
    
Called to process key events. You can override this to intercept all key events before they are dispatched to the window. Be sure to call this implementation for key events that should be handled normally.

Parameters:
event The key event.
Returns:
boolean Return true if this event was consumed.
 
     public boolean dispatchKeyEvent(KeyEvent event) {
         if (( != null) && (.onKey(thisevent.getKeyCode(), event))) {
             return true;
         }
         if (.superDispatchKeyEvent(event)) {
             return true;
         }
         return event.dispatch(this != null
                 ? .getKeyDispatcherState() : nullthis);
     }

    
Called to process touch screen events. You can override this to intercept all touch screen events before they are dispatched to the window. Be sure to call this implementation for touch screen events that should be handled normally.

Parameters:
ev The touch screen event.
Returns:
boolean Return true if this event was consumed.
 
     public boolean dispatchTouchEvent(MotionEvent ev) {
         if (.superDispatchTouchEvent(ev)) {
             return true;
         }
         return onTouchEvent(ev);
     }
    
    
Called to process trackball events. You can override this to intercept all trackball events before they are dispatched to the window. Be sure to call this implementation for trackball events that should be handled normally.

Parameters:
ev The trackball event.
Returns:
boolean Return true if this event was consumed.
 
     public boolean dispatchTrackballEvent(MotionEvent ev) {
         if (.superDispatchTrackballEvent(ev)) {
             return true;
         }
         return onTrackballEvent(ev);
     }
 
     public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
         event.setClassName(getClass().getName());
         event.setPackageName(.getPackageName());
 
         LayoutParams params = getWindow().getAttributes();
         boolean isFullScreen = (params.width == .) &&
             (params.height == .);
         event.setFullScreen(isFullScreen);
 
         return false;
     }

    
 
     public View onCreatePanelView(int featureId) {
         return null;
     }

    
 
     public boolean onCreatePanelMenu(int featureIdMenu menu) {
         if (featureId == .) {
             return onCreateOptionsMenu(menu);
         }
         
         return false;
     }

    
 
     public boolean onPreparePanel(int featureIdView viewMenu menu) {
         if (featureId == . && menu != null) {
             boolean goforit = onPrepareOptionsMenu(menu);
             return goforit && menu.hasVisibleItems();
         }
         return true;
     }

    
 
     public boolean onMenuOpened(int featureIdMenu menu) {
         return true;
     }

    
 
     public boolean onMenuItemSelected(int featureIdMenuItem item) {
         return false;
     }

    
 
     public void onPanelClosed(int featureIdMenu menu) {
     }

    
It is usually safe to proxy this call to the owner activity's Activity.onCreateOptionsMenu(android.view.Menu) if the client desires the same menu for this Dialog.

 
     public boolean onCreateOptionsMenu(Menu menu) {
         return true;
     }

    
It is usually safe to proxy this call to the owner activity's Activity.onPrepareOptionsMenu(android.view.Menu) if the client desires the same menu for this Dialog.

 
     public boolean onPrepareOptionsMenu(Menu menu) {
         return true;
     }

    
 
     public boolean onOptionsItemSelected(MenuItem item) {
         return false;
     }

    
 
     public void onOptionsMenuClosed(Menu menu) {
     }

    
 
     public void openOptionsMenu() {
     }
    
    
 
     public void closeOptionsMenu() {
     }

    
 
     public void onCreateContextMenu(ContextMenu menuView vContextMenuInfo menuInfo) {
     }

    
 
     public void registerForContextMenu(View view) {
         view.setOnCreateContextMenuListener(this);
     }
    
    
 
     public void unregisterForContextMenu(View view) {
         view.setOnCreateContextMenuListener(null);
     }
    
    
 
     public void openContextMenu(View view) {
         view.showContextMenu();
     }

    
 
     public boolean onContextItemSelected(MenuItem item) {
         return false;
     }
    
    
 
     public void onContextMenuClosed(Menu menu) {
     }
    
    
This hook is called when the user signals the desire to start a search.
 
     public boolean onSearchRequested() {
         final SearchManager searchManager = (SearchManager
                 .getSystemService(.);
 
         // associate search with owner activity
         final ComponentName appName = getAssociatedActivity();
         if (appName != null) {
             searchManager.startSearch(nullfalseappNamenullfalse);
             dismiss();
             return true;
         } else {
             return false;
         }
     }

    

Returns:
The activity associated with this dialog, or null if there is no assocaited activity.
 
     private ComponentName getAssociatedActivity() {
         Activity activity = ;
         Context context = getContext();
         while (activity == null && context != null) {
             if (context instanceof Activity) {
                 activity = (Activitycontext;  // found it!
             } else {
                 context = (context instanceof ContextWrapper) ?
                         ((ContextWrappercontext).getBaseContext() : // unwrap one level
                         null;                                         // done
             }
         }
         return activity == null ? null : activity.getComponentName();
     }


    
Request that key events come to this dialog. Use this if your dialog has no views with focus, but the dialog still wants a chance to process key events.

Parameters:
get true if the dialog should receive key events, false otherwise
See also:
android.view.Window.takeKeyEvents(boolean)
 
     public void takeKeyEvents(boolean get) {
         .takeKeyEvents(get);
     }

    
Enable extended window features. This is a convenience for calling getWindow().requestFeature().

Parameters:
featureId The desired feature as defined in android.view.Window.
Returns:
Returns true if the requested feature is supported and now enabled.
See also:
android.view.Window.requestFeature(int)
 
     public final boolean requestWindowFeature(int featureId) {
         return getWindow().requestFeature(featureId);
     }

    
 
     public final void setFeatureDrawableResource(int featureIdint resId) {
         getWindow().setFeatureDrawableResource(featureIdresId);
     }

    
 
     public final void setFeatureDrawableUri(int featureIdUri uri) {
         getWindow().setFeatureDrawableUri(featureIduri);
     }

    
 
     public final void setFeatureDrawable(int featureIdDrawable drawable) {
         getWindow().setFeatureDrawable(featureIddrawable);
     }

    
 
     public final void setFeatureDrawableAlpha(int featureIdint alpha) {
         getWindow().setFeatureDrawableAlpha(featureIdalpha);
     }
 
     public LayoutInflater getLayoutInflater() {
         return getWindow().getLayoutInflater();
     }

    
Sets whether this dialog is cancelable with the BACK key.
 
     public void setCancelable(boolean flag) {
          = flag;
     }

    
Sets whether this dialog is canceled when touched outside the window's bounds. If setting to true, the dialog is set to be cancelable if not already set.

Parameters:
cancel Whether the dialog should be canceled when touched outside the window.
 
     public void setCanceledOnTouchOutside(boolean cancel) {
         if (cancel && !) {
              = true;
         }
         
          = cancel;
     }
    
    
Cancel the dialog. This is essentially the same as calling dismiss(), but it will also call your android.content.DialogInterface.OnCancelListener (if registered).
 
     public void cancel() {
         if ( != null) {
             
             // Obtain a new message so this dialog can be re-used
             Message.obtain().sendToTarget();
         }
         dismiss();
     }

    
Set a listener to be invoked when the dialog is canceled.

This will only be invoked when the dialog is canceled, if the creator needs to know when it is dismissed in general, use setOnDismissListener(android.content.DialogInterface.OnDismissListener).

Parameters:
listener The android.content.DialogInterface.OnCancelListener to use.
 
     public void setOnCancelListener(final OnCancelListener listener) {
         if (listener != null) {
              = .obtainMessage(listener);
         } else {
              = null;
         }
     }

    
Set a message to be sent when the dialog is canceled.

Parameters:
msg The msg to send when the dialog is canceled.
See also:
setOnCancelListener(android.content.DialogInterface.OnCancelListener)
 
     public void setCancelMessage(final Message msg) {
          = msg;
     }

    
Set a listener to be invoked when the dialog is dismissed.

Parameters:
listener The android.content.DialogInterface.OnDismissListener to use.
 
     public void setOnDismissListener(final OnDismissListener listener) {
         if (listener != null) {
              = .obtainMessage(listener);
         } else {
              = null;
         }
     }

    
Sets a listener to be invoked when the dialog is shown.

Parameters:
listener The android.content.DialogInterface.OnShowListener to use.
 
     public void setOnShowListener(OnShowListener listener) {
         if (listener != null) {
              = .obtainMessage(listener);
         } else {
             = null;
        }
    }

    
Set a message to be sent when the dialog is dismissed.

Parameters:
msg The msg to send when the dialog is dismissed.
    public void setDismissMessage(final Message msg) {
         = msg;
    }

    
By default, this will use the owner Activity's suggested stream type.

    public final void setVolumeControlStream(int streamType) {
        getWindow().setVolumeControlStream(streamType);
    }

    
    public final int getVolumeControlStream() {
        return getWindow().getVolumeControlStream();
    }
    
    
Sets the callback that will be called if a key is dispatched to the dialog.
    public void setOnKeyListener(final OnKeyListener onKeyListener) {
         = onKeyListener;
    }
    private static final class ListenersHandler extends Handler {
        private WeakReference<DialogInterfacemDialog;
        public ListenersHandler(Dialog dialog) {
             = new WeakReference<DialogInterface>(dialog);
        }
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case :
                    ((OnDismissListenermsg.obj).onDismiss(.get());
                    break;
                case :
                    ((OnCancelListenermsg.obj).onCancel(.get());
                    break;
                case :
                    ((OnShowListenermsg.obj).onShow(.get());
                    break;
            }
        }
    }
New to GrepCode? Check out our FAQ X