Android源码解析之Dialog

来源:互联网 发布:晋江腾达陶瓷销售网络 编辑:程序博客网 时间:2024/05/29 11:42

出处—http://blog.csdn.net/lilu_leo/article/details/8220020


在学习设计模式建造者模式时,发现AlertDialog和它的内部类Builder就是比较典型的建造者模式,所以先分析下基类Dialog,然后再看子类AlertDialog和它的内部类Builder。



按照惯例,先看下类说明:

[java] view plaincopy
  1. Base class for Dialogs.  
  2.   
  3. Note: Activities provide a facility to manage the creation, saving and restoring of dialogs. See onCreateDialog(int), onPrepareDialog(int, Dialog), showDialog(int), and dismissDialog(int). If these methods are used, getOwnerActivity() will return the Activity that managed this dialog.  
  4.   
  5. 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:  
  6.   
  7.  getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,  
  8.          WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);  

Dialog是一系列Dialogs的基类。

注意:Activity提供了onCreateDialog(int)、onPrepareDialog(int, Dialog)和showDialog(int)这一些列方法用于管理dialog的创建、保存和恢复(注:关于onCreateDialog的用法见于:onCreateDialog方法及示例)。如果使用了以上方法,Dialog的getOwnerActivity方法就会返回创建Dialog的Activity。

如果你的Dialog不需要输入文本,想要显示在当前显示的输入法的上面,可以像下面代码通过设置WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM来实现(如果想要获取输入,则不用设置,默认获取焦点)

[java] view plaincopy
  1. getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,  
  2.         WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);  

使用WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM此标志位表示隐藏输入法。

看一下所用到的全局变量:

[java] view plaincopy
  1. public class Dialog implements DialogInterface, Window.Callback,  
  2.         KeyEvent.Callback, OnCreateContextMenuListener {  
  3.     private static final String TAG = "Dialog";  
  4.     private Activity mOwnerActivity;  
  5.       
  6.     final Context mContext;  
  7.     final WindowManager mWindowManager;  
  8.     Window mWindow;  
  9.     View mDecor;  
  10.     private ActionBarImpl mActionBar;  
  11.     /** 
  12.      * This field should be made private, so it is hidden from the SDK. 
  13.      * {@hide} 
  14.      */  
  15.     protected boolean mCancelable = true;  
  16.   
  17.     private String mCancelAndDismissTaken;  
  18.     private Message mCancelMessage;  
  19.     private Message mDismissMessage;  
  20.     private Message mShowMessage;  
  21.   
  22.     private OnKeyListener mOnKeyListener;  
  23.   
  24.     private boolean mCreated = false;  
  25.     private boolean mShowing = false;  
  26.     private boolean mCanceled = false;  
  27.   
  28.     private final Thread mUiThread;  
  29.     private final Handler mHandler = new Handler();  
  30.   
  31.     private static final int DISMISS = 0x43;  
  32.     private static final int CANCEL = 0x44;  
  33.     private static final int SHOW = 0x45;  
  34.   
  35.     private Handler mListenersHandler;  
  36.   
  37.     private ActionMode mActionMode;  
  38.   
  39.     private final Runnable mDismissAction = new Runnable() {  
  40.         public void run() {  
  41.             dismissDialog();  
  42.         }  
  43.     };  
变量都比较简单,这里不再详述。
Dialog类实现了DialogInterface, Window.Callback,KeyEvent.Callback, OnCreateContextMenuListener这些接口,今天看下DialogInterface接口,其他接口在Activity源码和Menu源码的时候再看。

[java] view plaincopy
  1. public interface DialogInterface {      
  2.     /** 
  3.      * The identifier for the positive button. 
  4.      */  
  5.     public static final int BUTTON_POSITIVE = -1;  
  6.   
  7.     /** 
  8.      * The identifier for the negative button.  
  9.      */  
  10.     public static final int BUTTON_NEGATIVE = -2;  
  11.   
  12.     /** 
  13.      * The identifier for the neutral button.  
  14.      */  
  15.     public static final int BUTTON_NEUTRAL = -3;  
  16.   
  17.     /** 
  18.      * @deprecated Use {@link #BUTTON_POSITIVE} 
  19.      */  
  20.     @Deprecated  
  21.     public static final int BUTTON1 = BUTTON_POSITIVE;  
  22.   
  23.     /** 
  24.      * @deprecated Use {@link #BUTTON_NEGATIVE} 
  25.      */  
  26.     @Deprecated  
  27.     public static final int BUTTON2 = BUTTON_NEGATIVE;  
  28.   
  29.     /** 
  30.      * @deprecated Use {@link #BUTTON_NEUTRAL} 
  31.      */  
  32.     @Deprecated  
  33.     public static final int BUTTON3 = BUTTON_NEUTRAL;  
  34.       
  35.     public void cancel();  
  36.   
  37.     public void dismiss();  
  38.   
  39.     /** 
  40.      * Interface used to allow the creator of a dialog to run some code when the 
  41.      * dialog is canceled. 
  42.      * <p> 
  43.      * This will only be called when the dialog is canceled, if the creator 
  44.      * needs to know when it is dismissed in general, use 
  45.      * {@link DialogInterface.OnDismissListener}. 
  46.      */  
  47.     interface OnCancelListener {  
  48.         /** 
  49.          * This method will be invoked when the dialog is canceled. 
  50.          *  
  51.          * @param dialog The dialog that was canceled will be passed into the 
  52.          *            method. 
  53.          */  
  54.         public void onCancel(DialogInterface dialog);  
  55.     }  
  56.   
  57.     /** 
  58.      * Interface used to allow the creator of a dialog to run some code when the 
  59.      * dialog is dismissed. 
  60.      */  
  61.     interface OnDismissListener {  
  62.         /** 
  63.          * This method will be invoked when the dialog is dismissed. 
  64.          *  
  65.          * @param dialog The dialog that was dismissed will be passed into the 
  66.          *            method. 
  67.          */  
  68.         public void onDismiss(DialogInterface dialog);  
  69.     }  
  70.   
  71.     /** 
  72.      * Interface used to allow the creator of a dialog to run some code when the 
  73.      * dialog is shown. 
  74.      */  
  75.     interface OnShowListener {  
  76.         /** 
  77.          * This method will be invoked when the dialog is shown. 
  78.          * 
  79.          * @param dialog The dialog that was shown will be passed into the 
  80.          *            method. 
  81.          */  
  82.         public void onShow(DialogInterface dialog);  
  83.     }  
  84.   
  85.     /** 
  86.      * Interface used to allow the creator of a dialog to run some code when an 
  87.      * item on the dialog is clicked.. 
  88.      */  
  89.     interface OnClickListener {  
  90.         /** 
  91.          * This method will be invoked when a button in the dialog is clicked. 
  92.          *  
  93.          * @param dialog The dialog that received the click. 
  94.          * @param which The button that was clicked (e.g. 
  95.          *            {@link DialogInterface#BUTTON1}) or the position 
  96.          *            of the item clicked. 
  97.          */  
  98.         /* TODO: Change to use BUTTON_POSITIVE after API council */  
  99.         public void onClick(DialogInterface dialog, int which);  
  100.     }  
  101.       
  102.     /** 
  103.      * Interface used to allow the creator of a dialog to run some code when an 
  104.      * item in a multi-choice dialog is clicked. 
  105.      */  
  106.     interface OnMultiChoiceClickListener {  
  107.         /** 
  108.          * This method will be invoked when an item in the dialog is clicked. 
  109.          *  
  110.          * @param dialog The dialog where the selection was made. 
  111.          * @param which The position of the item in the list that was clicked. 
  112.          * @param isChecked True if the click checked the item, else false. 
  113.          */  
  114.         public void onClick(DialogInterface dialog, int which, boolean isChecked);  
  115.     }  
  116.       
  117.     /** 
  118.      * Interface definition for a callback to be invoked when a key event is 
  119.      * dispatched to this dialog. The callback will be invoked before the key 
  120.      * event is given to the dialog. 
  121.      */  
  122.     interface OnKeyListener {  
  123.         /** 
  124.          * Called when a key is dispatched to a dialog. This allows listeners to 
  125.          * get a chance to respond before the dialog. 
  126.          *  
  127.          * @param dialog The dialog the key has been dispatched to. 
  128.          * @param keyCode The code for the physical key that was pressed 
  129.          * @param event The KeyEvent object containing full information about 
  130.          *            the event. 
  131.          * @return True if the listener has consumed the event, false otherwise. 
  132.          */  
  133.         public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event);  
  134.     }  
  135. }  

里面有代表三个button的变量,还有cancel()、dismiss()、还有OnCancelListener、OnDismissListener、OnShowListener、OnClickListener、OnMultiChoiceClickListener、OnKeyListener这些回调接口,会在AlertDialog源码解析中来说明这些方法。

下面是它的构造方法:

[java] view plaincopy
  1. /** 
  2.      * Create a Dialog window that uses the default dialog frame style. 
  3.      *  
  4.      * @param context The Context the Dialog is to run it.  In particular, it 
  5.      *                uses the window manager and theme in this context to 
  6.      *                present its UI. 
  7.      */  
  8.     public Dialog(Context context) {  
  9.         this(context, 0true);  
  10.     }  
  11.   
  12.     /** 
  13.      * Create a Dialog window that uses a custom dialog style. 
  14.      *  
  15.      * @param context The Context in which the Dialog should run. In particular, it 
  16.      *                uses the window manager and theme from this context to 
  17.      *                present its UI. 
  18.      * @param theme A style resource describing the theme to use for the  
  19.      * window. See <a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">Style  
  20.      * and Theme Resources</a> for more information about defining and using  
  21.      * styles.  This theme is applied on top of the current theme in  
  22.      * <var>context</var>.  If 0, the default dialog theme will be used. 
  23.      */  
  24.     public Dialog(Context context, int theme) {  
  25.         this(context, theme, true);  
  26.     }  
  27.   
  28.     Dialog(Context context, int theme, boolean createContextWrapper) {  
  29.         if (theme == 0) {  
  30.             TypedValue outValue = new TypedValue();  
  31.             context.getTheme().resolveAttribute(com.android.internal.R.attr.dialogTheme,  
  32.                     outValue, true);  
  33.             theme = outValue.resourceId;  
  34.         }  
  35.   
  36.         mContext = createContextWrapper ? new ContextThemeWrapper(context, theme) : context;  
  37.         mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);  
  38.         Window w = PolicyManager.makeNewWindow(mContext);  
  39.         mWindow = w;  
  40.         w.setCallback(this);  
  41.         w.setWindowManager(mWindowManager, nullnull);  
  42.         w.setGravity(Gravity.CENTER);  
  43.         mUiThread = Thread.currentThread();  
  44.         mListenersHandler = new ListenersHandler(this);  
  45.     }  
  46.       
  47.     /** 
  48.      * @deprecated 
  49.      * @hide 
  50.      */  
  51.     @Deprecated  
  52.     protected Dialog(Context context, boolean cancelable,  
  53.             Message cancelCallback) {  
  54.         this(context);  
  55.         mCancelable = cancelable;  
  56.         mCancelMessage = cancelCallback;  
  57.     }  
  58.   
  59.     protected Dialog(Context context, boolean cancelable,  
  60.             OnCancelListener cancelListener) {  
  61.         this(context);  
  62.         mCancelable = cancelable;  
  63.         setOnCancelListener(cancelListener);  
  64.     }  
第一个构造方法是使用对话框风格,第二个构造方法使用自定义的对话框风格,这两个构造方法都是调用的下面的Dialog方法,我们注意到他的权限是缺省,就是我我们在外部不能直接使用该构造方法。

[java] view plaincopy
  1. Dialog(Context context, int theme, boolean createContextWrapper) {  
  2.         if (theme == 0) {  
  3.             TypedValue outValue = new TypedValue();  
  4.             context.getTheme().resolveAttribute(com.android.internal.R.attr.dialogTheme,  
  5.                     outValue, true);  
  6.             theme = outValue.resourceId;  
  7.         }  
  8.   
  9.         mContext = createContextWrapper ? new ContextThemeWrapper(context, theme) : context;  
  10.         mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);  
  11.         Window w = PolicyManager.makeNewWindow(mContext);  
  12.         mWindow = w;  
  13.         w.setCallback(this);  
  14.         w.setWindowManager(mWindowManager, nullnull);  
  15.         w.setGravity(Gravity.CENTER);  
  16.         mUiThread = Thread.currentThread();  
  17.         mListenersHandler = new ListenersHandler(this);  
  18.     }  

如果theme为0,则使用系统定义的风格,然后初始化mWindow。

第三个构造方法被Deprecated掉,不看,第四个可以实现取消回调。

再看下面的两个方法:

[java] view plaincopy
  1. /** 
  2.      * Retrieve the Context this Dialog is running in. 
  3.      *  
  4.      * @return Context The Context used by the Dialog. 
  5.      */  
  6.     public final Context getContext() {  
  7.         return mContext;  
  8.     }  
  9.   
  10.     /** 
  11.      * Retrieve the {@link ActionBar} attached to this dialog, if present. 
  12.      * 
  13.      * @return The ActionBar attached to the dialog or null if no ActionBar is present. 
  14.      */  
  15.     public ActionBar getActionBar() {  
  16.         return mActionBar;  
  17.     }  

获取Dialog运行的山下文环境和ActionBar。

[java] view plaincopy
  1. /** 
  2.      * Sets the Activity that owns this dialog. An example use: This Dialog will 
  3.      * use the suggested volume control stream of the Activity. 
  4.      *  
  5.      * @param activity The Activity that owns this dialog. 
  6.      */  
  7.     public final void setOwnerActivity(Activity activity) {  
  8.         mOwnerActivity = activity;  
  9.           
  10.         getWindow().setVolumeControlStream(mOwnerActivity.getVolumeControlStream());  
  11.     }  
  12.   
  13.     /** 
  14.      * Returns the Activity that owns this Dialog. For example, if 
  15.      * {@link Activity#showDialog(int)} is used to show this Dialog, that 
  16.      * Activity will be the owner (by default). Depending on how this dialog was 
  17.      * created, this may return null. 
  18.      *  
  19.      * @return The Activity that owns this Dialog. 
  20.      */  
  21.     public final Activity getOwnerActivity() {  
  22.         return mOwnerActivity;  
  23.     }  

设置和获取Dialog所属的Activity和获取(如果在onCreate()之外创建dialog,它不会附属于任何的Activity,可以使用dialog的setOwnerActivity(Activity)来设置),调用showDialog方法的Activity默认情况下就是要返回的Activity。

[java] view plaincopy
  1. /** 
  2.  * @return Whether the dialog is currently showing. 
  3.  */  
  4. public boolean isShowing() {  
  5.     return mShowing;  
  6. }  

判断当前Dialog是否显示。

[java] view plaincopy
  1. /** 
  2.      * Start the dialog and display it on screen.  The window is placed in the 
  3.      * application layer and opaque.  Note that you should not override this 
  4.      * method to do initialization when the dialog is shown, instead implement 
  5.      * that in {@link #onStart}. 
  6.      */  
  7.     public void show() {  
  8.         if (mShowing) {  
  9.             if (mDecor != null) {  
  10.                 if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {  
  11.                     mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);  
  12.                 }  
  13.                 mDecor.setVisibility(View.VISIBLE);  
  14.             }  
  15.             return;  
  16.         }  
  17.   
  18.         mCanceled = false;  
  19.           
  20.         if (!mCreated) {  
  21.             dispatchOnCreate(null);  
  22.         }  
  23.   
  24.         onStart();  
  25.         mDecor = mWindow.getDecorView();  
  26.   
  27.         if (mActionBar == null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {  
  28.             mActionBar = new ActionBarImpl(this);  
  29.         }  
  30.   
  31.         WindowManager.LayoutParams l = mWindow.getAttributes();  
  32.         if ((l.softInputMode  
  33.                 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {  
  34.             WindowManager.LayoutParams nl = new WindowManager.LayoutParams();  
  35.             nl.copyFrom(l);  
  36.             nl.softInputMode |=  
  37.                     WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;  
  38.             l = nl;  
  39.         }  
  40.   
  41.         try {  
  42.             mWindowManager.addView(mDecor, l);  
  43.             mShowing = true;  
  44.       
  45.             sendShowMessage();  
  46.         } finally {  
  47.         }  
  48.     }  

显示创建的dialog,它是不透明的并且你不能在它显示的时候重载show方法,可以在onStart方法里实现。当mCreate为false的时候调用了dispatchOnCreate方法同时里面调用onCreate方法确保Dialog被初始化:

[java] view plaincopy
  1. // internal method to make sure mcreated is set properly without requiring  
  2.     // users to call through to super in onCreate  
  3.     void dispatchOnCreate(Bundle savedInstanceState) {  
  4.         if (!mCreated) {  
  5.             onCreate(savedInstanceState);  
  6.             mCreated = true;  
  7.         }  
  8.     }  
  9.   
  10.     /** 
  11.      * Similar to {@link Activity#onCreate}, you should initialize your dialog 
  12.      * in this method, including calling {@link #setContentView}. 
  13.      * @param savedInstanceState If this dialog is being reinitalized after a 
  14.      *     the hosting activity was previously shut down, holds the result from 
  15.      *     the most recent call to {@link #onSaveInstanceState}, or null if this 
  16.      *     is the first time. 
  17.      */  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.     }  

[java] view plaincopy
  1. /** 
  2.      * Called when the dialog is starting. 
  3.      */  
  4.     protected void onStart() {  
  5.         if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);  
  6.     }  


一切都创建好以后:调用sendShowMessage方法向UI线程发送一个消息:

[java] view plaincopy
  1. private void sendShowMessage() {  
  2.         if (mShowMessage != null) {  
  3.             // Obtain a new message so this dialog can be re-used  
  4.             Message.obtain(mShowMessage).sendToTarget();  
  5.         }  
  6.     }  

隐藏Dialog(但不是去除Dialog):

[java] view plaincopy
  1. /** 
  2.      * Hide the dialog, but do not dismiss it. 
  3.      */  
  4.     public void hide() {  
  5.         if (mDecor != null) {  
  6.             mDecor.setVisibility(View.GONE);  
  7.         }  
  8.     }  

去除Dialog:

[java] view plaincopy
  1. /** 
  2.  * Dismiss this dialog, removing it from the screen. This method can be 
  3.  * invoked safely from any thread.  Note that you should not override this 
  4.  * method to do cleanup when the dialog is dismissed, instead implement 
  5.  * that in {@link #onStop}. 
  6.  */  
  7. public void dismiss() {  
  8.     if (Thread.currentThread() != mUiThread) {  
  9.         mHandler.post(mDismissAction);  
  10.     } else {  
  11.         mHandler.removeCallbacks(mDismissAction);  
  12.         mDismissAction.run();  
  13.     }  
  14. }  

从屏幕上去除dialog,这个方法在任何线程中都是安全的,注意当dialog被取消,不要重写这个方法。可以在onStop方法里面调用dismiss方法。

里面执行了mDismissAction这个runnable:

[java] view plaincopy
  1. private final Runnable mDismissAction = new Runnable() {  
  2.         public void run() {  
  3.             dismissDialog();  
  4.         }  
  5.     };  

 主要执行dismissDialog方法:

[java] view plaincopy
  1. void dismissDialog() {  
  2.        if (mDecor == null || !mShowing) {  
  3.            return;  
  4.        }  
  5.   
  6.        if (mWindow.isDestroyed()) {  
  7.            Log.e(TAG, "Tried to dismissDialog() but the Dialog's window was already destroyed!");  
  8.            return;  
  9.        }  
  10.   
  11.        try {  
  12.            mWindowManager.removeView(mDecor);  
  13.        } finally {  
  14.            if (mActionMode != null) {  
  15.                mActionMode.finish();  
  16.            }  
  17.            mDecor = null;  
  18.            mWindow.closeAllPanels();  
  19.            onStop();  
  20.            mShowing = false;  
  21.              
  22.            sendDismissMessage();  
  23.        }  
  24.    }  

里面主要任务就是销毁一切资源,然后里面调用了onStop方法:

[java] view plaincopy
  1. /** 
  2.  * Called to tell you that you're stopping. 
  3.  */  
  4. protected void onStop() {  
  5.     if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);  
  6. }  

把ActionBar功能设为false。上面还调用了senDismissMessage方法:

[java] view plaincopy
  1. private void sendDismissMessage() {  
  2.         if (mDismissMessage != null) {  
  3.             // Obtain a new message so this dialog can be re-used  
  4.             Message.obtain(mDismissMessage).sendToTarget();  
  5.         }  
  6.     }  

下一个就是保持状态的onSaveInstanceState和从保存状态中恢复onRestoreInstanceState:

[java] view plaincopy
  1. /** 
  2.  * Saves the state of the dialog into a bundle. 
  3.  * 
  4.  * The default implementation saves the state of its view hierarchy, so you'll 
  5.  * likely want to call through to super if you override this to save additional 
  6.  * state. 
  7.  * @return A bundle with the state of the dialog. 
  8.  */  
  9. public Bundle onSaveInstanceState() {  
  10.     Bundle bundle = new Bundle();  
  11.     bundle.putBoolean(DIALOG_SHOWING_TAG, mShowing);  
  12.     if (mCreated) {  
  13.         bundle.putBundle(DIALOG_HIERARCHY_TAG, mWindow.saveHierarchyState());  
  14.     }  
  15.     return bundle;  
  16. }  
  17.   
  18. /** 
  19.  * Restore the state of the dialog from a previously saved bundle. 
  20.  * 
  21.  * The default implementation restores the state of the dialog's view 
  22.  * hierarchy that was saved in the default implementation of {@link #onSaveInstanceState()}, 
  23.  * so be sure to call through to super when overriding unless you want to 
  24.  * do all restoring of state yourself. 
  25.  * @param savedInstanceState The state of the dialog previously saved by 
  26.  *     {@link #onSaveInstanceState()}. 
  27.  */  
  28. public void onRestoreInstanceState(Bundle savedInstanceState) {  
  29.     final Bundle dialogHierarchyState = savedInstanceState.getBundle(DIALOG_HIERARCHY_TAG);  
  30.     if (dialogHierarchyState == null) {  
  31.         // dialog has never been shown, or onCreated, nothing to restore.  
  32.         return;  
  33.     }  
  34.     dispatchOnCreate(savedInstanceState);  
  35.     mWindow.restoreHierarchyState(dialogHierarchyState);  
  36.     if (savedInstanceState.getBoolean(DIALOG_SHOWING_TAG)) {  
  37.         show();  
  38.     }  
  39. }  
下一个方法是获取当前的Window用于直接访问其API而不是通过Activity或者Screen:

[java] view plaincopy
  1. /** 
  2.  * Retrieve the current Window for the activity.  This can be used to 
  3.  * directly access parts of the Window API that are not available 
  4.  * through Activity/Screen. 
  5.  *  
  6.  * @return Window The current window, or null if the activity is not 
  7.  *         visual. 
  8.  */  
  9. public Window getWindow() {  
  10.     return mWindow;  
  11. }  

再获取当前拥有焦点的View:

[java] view plaincopy
  1. /** 
  2.   * Call {@link android.view.Window#getCurrentFocus} on the 
  3.   * Window if this Activity to return the currently focused view. 
  4.   *  
  5.   * @return View The current View with focus or null. 
  6.   *  
  7.   * @see #getWindow 
  8.   * @see android.view.Window#getCurrentFocus 
  9.   */  
  10.  public View getCurrentFocus() {  
  11.      return mWindow != null ? mWindow.getCurrentFocus() : null;  
  12.  }  

还可以在onStart方法里面调用findViewById来通过ID获取xml文件中的View:

[java] view plaincopy
  1. /** 
  2.      * Finds a view that was identified by the id attribute from the XML that 
  3.      * was processed in {@link #onStart}. 
  4.      * 
  5.      * @param id the identifier of the view to find 
  6.      * @return The view if found or null otherwise. 
  7.      */  
  8.     public View findViewById(int id) {  
  9.         return mWindow.findViewById(id);  
  10.     }  

也可以通过ID和View设置Dialog的View:

[java] view plaincopy
  1. /** 
  2.  * Set the screen content from a layout resource.  The resource will be 
  3.  * inflated, adding all top-level views to the screen. 
  4.  *  
  5.  * @param layoutResID Resource ID to be inflated. 
  6.  */  
  7. public void setContentView(int layoutResID) {  
  8.     mWindow.setContentView(layoutResID);  
  9. }  
  10.   
  11. /** 
  12.  * Set the screen content to an explicit view.  This view is placed 
  13.  * directly into the screen's view hierarchy.  It can itself be a complex 
  14.  * view hierarhcy. 
  15.  *  
  16.  * @param view The desired content to display. 
  17.  */  
  18. public void setContentView(View view) {  
  19.     mWindow.setContentView(view);  
  20. }  

还可以添加View的属性:

[java] view plaincopy
  1. /** 
  2.      * Set the screen content to an explicit view.  This view is placed 
  3.      * directly into the screen's view hierarchy.  It can itself be a complex 
  4.      * view hierarhcy. 
  5.      *  
  6.      * @param view The desired content to display. 
  7.      * @param params Layout parameters for the view. 
  8.      */  
  9.     public void setContentView(View view, ViewGroup.LayoutParams params) {  
  10.         mWindow.setContentView(view, params);  
  11.     }  

在Dialog已存在的View的基础上,再添加一个View:

[java] view plaincopy
  1. /** 
  2.   * Add an additional content view to the screen.  Added after any existing 
  3.   * ones in the screen -- existing views are NOT removed. 
  4.   *  
  5.   * @param view The desired content to display. 
  6.   * @param params Layout parameters for the view. 
  7.   */  
  8.  public void addContentView(View view, ViewGroup.LayoutParams params) {  
  9.      mWindow.addContentView(view, params);  
  10.  }  

先前的View并不会被去除。

为Dialog设置标题:

[java] view plaincopy
  1. /** 
  2.  * Set the title text for this dialog's window. 
  3.  *  
  4.  * @param title The new text to display in the title. 
  5.  */  
  6. public void setTitle(CharSequence title) {  
  7.     mWindow.setTitle(title);  
  8.     mWindow.getAttributes().setTitle(title);  
  9. }  
  10.   
  11. /** 
  12.  * Set the title text for this dialog's window. The text is retrieved 
  13.  * from the resources with the supplied identifier. 
  14.  * 
  15.  * @param titleId the title's text resource identifier 
  16.  */  
  17. public void setTitle(int titleId) {  
  18.     setTitle(mContext.getText(titleId));  
  19. }  

onKeyDown只处理了back键:

[java] view plaincopy
  1. /** 
  2.      * A key was pressed down. 
  3.      *  
  4.      * <p>If the focused view didn't want this event, this method is called. 
  5.      * 
  6.      * <p>The default implementation consumed the KEYCODE_BACK to later 
  7.      * handle it in {@link #onKeyUp}. 
  8.      * 
  9.      * @see #onKeyUp 
  10.      * @see android.view.KeyEvent 
  11.      */  
  12.     public boolean onKeyDown(int keyCode, KeyEvent event) {  
  13.         if (keyCode == KeyEvent.KEYCODE_BACK) {  
  14.             event.startTracking();  
  15.             return true;  
  16.         }  
  17.   
  18.         return false;  
  19.       

长按则不做任何处理:

[java] view plaincopy
  1. /** 
  2.  * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 
  3.  * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 
  4.  * the event). 
  5.  */  
  6. public boolean onKeyLongPress(int keyCode, KeyEvent event) {  
  7.     return false;  
  8. }  

按键松开:

[java] view plaincopy
  1. /** 
  2.  * A key was released. 
  3.  *  
  4.  * <p>The default implementation handles KEYCODE_BACK to close the 
  5.  * dialog. 
  6.  * 
  7.  * @see #onKeyDown 
  8.  * @see KeyEvent 
  9.  */  
  10. public boolean onKeyUp(int keyCode, KeyEvent event) {  
  11.     if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()  
  12.             && !event.isCanceled()) {  
  13.         onBackPressed();  
  14.         return true;  
  15.     }  
  16.     return false;  
  17. }  

还是只处理back键,调用onBackPressed:

[java] view plaincopy
  1. /** 
  2.  * Called when the dialog has detected the user's press of the back 
  3.  * key.  The default implementation simply cancels the dialog (only if 
  4.  * it is cancelable), but you can override this to do whatever you want. 
  5.  */  
  6. public void onBackPressed() {  
  7.     if (mCancelable) {  
  8.         cancel();  
  9.     }  
  10. }  

这个方法默认实现当你按返回键的时候简单的取消dialog,如果你想实现其他功能,可以重写它。

[java] view plaincopy
  1. /** 
  2.      * Called when an key shortcut event is not handled by any of the views in the Dialog. 
  3.      * Override this method to implement global key shortcuts for the Dialog. 
  4.      * Key shortcuts can also be implemented by setting the 
  5.      * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 
  6.      * 
  7.      * @param keyCode The value in event.getKeyCode(). 
  8.      * @param event Description of the key event. 
  9.      * @return True if the key shortcut was handled. 
  10.      */  
  11.     public boolean onKeyShortcut(int keyCode, KeyEvent event) {  
  12.         return false;  
  13.       

对多次重复按键不做任何响应:

[java] view plaincopy
  1. /** 
  2.   * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 
  3.   * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 
  4.   * the event). 
  5.   */  
  6.  public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {  
  7.      return false;  
  8.  }  


对于快捷键,不做任何处理。

[java] view plaincopy
  1. /** 
  2.      * Called when a touch screen event was not handled by any of the views 
  3.      * under it. This is most useful to process touch events that happen outside 
  4.      * of your window bounds, where there is no view to receive it. 
  5.      *  
  6.      * @param event The touch screen event being processed. 
  7.      * @return Return true if you have consumed the event, false if you haven't. 
  8.      *         The default implementation will cancel the dialog when a touch 
  9.      *         happens outside of the window bounds. 
  10.      */  
  11.     public boolean onTouchEvent(MotionEvent event) {  
  12.         if (mCancelable && mShowing && mWindow.shouldCloseOnTouch(mContext, event)) {  
  13.             cancel();  
  14.             return true;  
  15.         }  
  16.           
  17.         return false;  
  18.     }  

onTouch事件,当发生在dialog区域内,不做任何事,发生在区域外,去除Dialog。

[java] view plaincopy
  1. /** 
  2.      * Cancel the dialog.  This is essentially the same as calling {@link #dismiss()}, but it will 
  3.      * also call your {@link DialogInterface.OnCancelListener} (if registered). 
  4.      */  
  5.     public void cancel() {  
  6.         if (!mCanceled && mCancelMessage != null) {  
  7.             mCanceled = true;  
  8.             // Obtain a new message so this dialog can be re-used  
  9.             Message.obtain(mCancelMessage).sendToTarget();  
  10.         }  
  11.         dismiss();  
  12.     }  

取消dialog。

好吧,下面还有轨迹球:

[java] view plaincopy
  1. /** 
  2.   * Called when the trackball was moved and not handled by any of the 
  3.   * views inside of the activity.  So, for example, if the trackball moves 
  4.   * while focus is on a button, you will receive a call here because 
  5.   * buttons do not normally do anything with trackball events.  The call 
  6.   * here happens <em>before</em> trackball movements are converted to 
  7.   * DPAD key events, which then get sent back to the view hierarchy, and 
  8.   * will be processed at the point for things like focus navigation. 
  9.   *  
  10.   * @param event The trackball event being processed. 
  11.   *  
  12.   * @return Return true if you have consumed the event, false if you haven't. 
  13.   * The default implementation always returns false. 
  14.   */  
  15.  public boolean onTrackballEvent(MotionEvent event) {  
  16.      return false;  
  17.  }  

实现该方法来处理触屏事件. 一般的动作事件,描述操纵杆移动、鼠标悬停、触控板事件、滚轮移动以及其他输入事件. 动作 源指定了接收到事件的类型.实现该方法必须 必须在处理事件之前检测动作源的标志位.下面是如果处理的示例代码. 发生源为 SOURCE_CLASS_POINTER 的动作事件发送到光标下的视图. 所有其他发生源的动作时间发送到拥有焦点的视图.这里还是不做任何处理。(众所周知,现在轨迹球已经基本消失)

当Window的属性发生改变时,会重新设置属性:

[java] view plaincopy
  1. public void onWindowAttributesChanged(WindowManager.LayoutParams params) {  
  2.         if (mDecor != null) {  
  3.             mWindowManager.updateViewLayout(mDecor, params);  
  4.         }  
  5.     }  
当内容、焦点、Window添加或移除View都没有处理。
[java] view plaincopy
  1. public void onContentChanged() {  
  2.    }  
  3.      
  4.    public void onWindowFocusChanged(boolean hasFocus) {  
  5.    }  
  6.   
  7.    public void onAttachedToWindow() {  
  8.    }  
  9.      
  10.    public void onDetachedFromWindow() {  
  11.    }  

下面几个方法就是把一系列点击、触屏、滑动轨迹球等事件往上分发传递否则就调用本类中方法处理,你也可以在重写这些方法使它在向上分发传递事件之前做一些自己的事。

[java] view plaincopy
  1. /** 
  2.  * Called to process key events.  You can override this to intercept all  
  3.  * key events before they are dispatched to the window.  Be sure to call  
  4.  * this implementation for key events that should be handled normally. 
  5.  *  
  6.  * @param event The key event. 
  7.  *  
  8.  * @return boolean Return true if this event was consumed. 
  9.  */  
  10. public boolean dispatchKeyEvent(KeyEvent event) {  
  11.     if ((mOnKeyListener != null) && (mOnKeyListener.onKey(this, event.getKeyCode(), event))) {  
  12.         return true;  
  13.     }  
  14.     if (mWindow.superDispatchKeyEvent(event)) {  
  15.         return true;  
  16.     }  
  17.     return event.dispatch(this, mDecor != null  
  18.             ? mDecor.getKeyDispatcherState() : nullthis);  
  19. }  
  20.   
  21. /** 
  22.  * Called to process a key shortcut event. 
  23.  * You can override this to intercept all key shortcut events before they are 
  24.  * dispatched to the window.  Be sure to call this implementation for key shortcut 
  25.  * events that should be handled normally. 
  26.  * 
  27.  * @param event The key shortcut event. 
  28.  * @return True if this event was consumed. 
  29.  */  
  30. public boolean dispatchKeyShortcutEvent(KeyEvent event) {  
  31.     if (mWindow.superDispatchKeyShortcutEvent(event)) {  
  32.         return true;  
  33.     }  
  34.     return onKeyShortcut(event.getKeyCode(), event);  
  35. }  
  36.   
  37. /** 
  38.  * Called to process touch screen events.  You can override this to 
  39.  * intercept all touch screen events before they are dispatched to the 
  40.  * window.  Be sure to call this implementation for touch screen events 
  41.  * that should be handled normally. 
  42.  *  
  43.  * @param ev The touch screen event. 
  44.  *  
  45.  * @return boolean Return true if this event was consumed. 
  46.  */  
  47. public boolean dispatchTouchEvent(MotionEvent ev) {  
  48.     if (mWindow.superDispatchTouchEvent(ev)) {  
  49.         return true;  
  50.     }  
  51.     return onTouchEvent(ev);  
  52. }  
  53.   
  54. /** 
  55.  * Called to process trackball events.  You can override this to 
  56.  * intercept all trackball events before they are dispatched to the 
  57.  * window.  Be sure to call this implementation for trackball events 
  58.  * that should be handled normally. 
  59.  *  
  60.  * @param ev The trackball event. 
  61.  *  
  62.  * @return boolean Return true if this event was consumed. 
  63.  */  
  64. public boolean dispatchTrackballEvent(MotionEvent ev) {  
  65.     if (mWindow.superDispatchTrackballEvent(ev)) {  
  66.         return true;  
  67.     }  
  68.     return onTrackballEvent(ev);  
  69. }  
  70.   
  71. /** 
  72.  * Called to process generic motion events.  You can override this to 
  73.  * intercept all generic motion events before they are dispatched to the 
  74.  * window.  Be sure to call this implementation for generic motion events 
  75.  * that should be handled normally. 
  76.  * 
  77.  * @param ev The generic motion event. 
  78.  * 
  79.  * @return boolean Return true if this event was consumed. 
  80.  */  
  81. public boolean dispatchGenericMotionEvent(MotionEvent ev) {  
  82.     if (mWindow.superDispatchGenericMotionEvent(ev)) {  
  83.         return true;  
  84.     }  
  85.     return onGenericMotionEvent(ev);  
  86. }  

分发传递dispatchPopulateAccessibilityEvent:

[java] view plaincopy
  1. public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {  
  2.         event.setClassName(getClass().getName());  
  3.         event.setPackageName(mContext.getPackageName());  
  4.   
  5.         LayoutParams params = getWindow().getAttributes();  
  6.         boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&  
  7.             (params.height == LayoutParams.MATCH_PARENT);  
  8.         event.setFullScreen(isFullScreen);  
  9.   
  10.         return false;  
  11.     }  

[java] view plaincopy
  1. /** 
  2.      * @see Activity#onCreatePanelView(int) 
  3.      */  
  4.     public View onCreatePanelView(int featureId) {  
  5.         return null;  
  6.     }  
实现Window.Callback接口的onCreatePanelView方法,简单的实现就是返回null。

[java] view plaincopy
  1. /** 
  2.      * @see Activity#onCreatePanelMenu(int, Menu) 
  3.      */  
  4.     public boolean onCreatePanelMenu(int featureId, Menu menu) {  
  5.         if (featureId == Window.FEATURE_OPTIONS_PANEL) {  
  6.             return onCreateOptionsMenu(menu);  
  7.         }  
  8.           
  9.         return false;  
  10.     }  

创建一个菜单,实现Window.Callback接口的onCreatePanelMenu方法。

[java] view plaincopy
  1. /** 
  2.  * @see Activity#onPreparePanel(int, View, Menu) 
  3.  */  
  4. public boolean onPreparePanel(int featureId, View view, Menu menu) {  
  5.     if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {  
  6.         boolean goforit = onPrepareOptionsMenu(menu);  
  7.         return goforit && menu.hasVisibleItems();  
  8.     }  
  9.     return true;  
  10. }  

实现Window.Callback接口的onPreparePanel方法。每次当panel窗口显示前,都会调用该函数,返回true显示,false则不显示。

[java] view plaincopy
  1. /** 
  2.  * @see Activity#onMenuOpened(int, Menu) 
  3.  */  
  4. public boolean onMenuOpened(int featureId, Menu menu) {  
  5.     if (featureId == Window.FEATURE_ACTION_BAR) {  
  6.         mActionBar.dispatchMenuVisibilityChanged(true);  
  7.     }  
  8.     return true;  
  9. }  

实现Window.Callback接口的onMenuOpened方法。当菜单打开时,调用该方法。

[java] view plaincopy
  1. /** 
  2.  * @see Activity#onMenuItemSelected(int, MenuItem) 
  3.  */  
  4. public boolean onMenuItemSelected(int featureId, MenuItem item) {  
  5.     return false;  
  6. }  

实现Window.Callback接口的onMenuItemSelected方法。不做任何处理。

[java] view plaincopy
  1. /** 
  2.  * @see Activity#onPanelClosed(int, Menu) 
  3.  */  
  4. public void onPanelClosed(int featureId, Menu menu) {  
  5.     if (featureId == Window.FEATURE_ACTION_BAR) {  
  6.         mActionBar.dispatchMenuVisibilityChanged(false);  
  7.     }  
  8. }  
实现Window.Callback接口的onPanelClosed方法。当featureId为Window.FEATURE_ACTION_BAR时,修改ActionBar的分发事件。

[java] view plaincopy
  1. /** 
  2.  * It is usually safe to proxy this call to the owner activity's 
  3.  * {@link Activity#onCreateOptionsMenu(Menu)} if the client desires the same 
  4.  * menu for this Dialog. 
  5.  *  
  6.  * @see Activity#onCreateOptionsMenu(Menu) 
  7.  * @see #getOwnerActivity() 
  8.  */  
  9. public boolean onCreateOptionsMenu(Menu menu) {  
  10.     return true;  
  11. }  
调用创建该Dialog的Activity的onCreateOptionMenu方法。

[java] view plaincopy
  1. /** 
  2.      * It is usually safe to proxy this call to the owner activity's 
  3.      * {@link Activity#onPrepareOptionsMenu(Menu)} if the client desires the 
  4.      * same menu for this Dialog. 
  5.      *  
  6.      * @see Activity#onPrepareOptionsMenu(Menu) 
  7.      * @see #getOwnerActivity() 
  8.      */  
  9.     public boolean onPrepareOptionsMenu(Menu menu) {  
  10.         return true;  
  11.     }  

调用创建Activity的onCreatePrepareOptionsMenu方法。

[java] view plaincopy
  1. /** 
  2.  * @see Activity#onOptionsItemSelected(MenuItem) 
  3.  */  
  4. public boolean onOptionsItemSelected(MenuItem item) {  
  5.     return false;  
  6. }  
  7.   
  8. /** 
  9.  * @see Activity#onOptionsMenuClosed(Menu) 
  10.  */  
  11. public void onOptionsMenuClosed(Menu menu) {  
  12. }  

对选项菜单的操作,两个都未做处理。

[java] view plaincopy
  1. /** 
  2.  * @see Activity#openOptionsMenu() 
  3.  */  
  4. public void openOptionsMenu() {  
  5.     mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);  
  6. }  
  7.   
  8. /** 
  9.  * @see Activity#closeOptionsMenu() 
  10.  */  
  11. public void closeOptionsMenu() {  
  12.     mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);  
  13. }  
  14.   
  15. /** 
  16.  * @see Activity#invalidateOptionsMenu() 
  17.  */  
  18. public void invalidateOptionsMenu() {  
  19.     mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);  
  20. }  

对选项菜单的三个操作,均是调用的Window类里面的方法。

[java] view plaincopy
  1. /** 
  2.      * @see Activity#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) 
  3.      */  
  4.     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {  
  5.     }  

创建上下文菜单,未处理。

为一个View注册和取消注册一个上下文菜单:

[java] view plaincopy
  1. /** 
  2.  * @see Activity#registerForContextMenu(View) 
  3.  */  
  4. public void registerForContextMenu(View view) {  
  5.     view.setOnCreateContextMenuListener(this);  
  6. }  
  7.   
  8. /** 
  9.  * @see Activity#unregisterForContextMenu(View) 
  10.  */  
  11. public void unregisterForContextMenu(View view) {  
  12.     view.setOnCreateContextMenuListener(null);  
  13. }  

打开一个View的上下文菜单:

[java] view plaincopy
  1. /** 
  2.   * @see Activity#openContextMenu(View) 
  3.   */  
  4.  public void openContextMenu(View view) {  
  5.      view.showContextMenu();  
  6.  }  

[java] view plaincopy
  1. /** 
  2.  * @see Activity#onContextItemSelected(MenuItem) 
  3.  */  
  4. public boolean onContextItemSelected(MenuItem item) {  
  5.     return false;  
  6. }  

上下文菜单选项被处理,未做任何事情。

[java] view plaincopy
  1. /** 
  2.  * @see Activity#onContextMenuClosed(Menu) 
  3.  */  
  4. public void onContextMenuClosed(Menu menu) {  
  5. }  

上下文菜单关闭。

[java] view plaincopy
  1. /** 
  2.      * This hook is called when the user signals the desire to start a search. 
  3.      */  
  4.     public boolean onSearchRequested() {  
  5.         final SearchManager searchManager = (SearchManager) mContext  
  6.                 .getSystemService(Context.SEARCH_SERVICE);  
  7.   
  8.         // associate search with owner activity  
  9.         final ComponentName appName = getAssociatedActivity();  
  10.         if (appName != null && searchManager.getSearchableInfo(appName) != null) {  
  11.             searchManager.startSearch(nullfalse, appName, nullfalse);  
  12.             dismiss();  
  13.             return true;  
  14.         } else {  
  15.             return false;  
  16.         }  
  17.     }  

这个钩子方法会在用户想要搜索的时候被调用。

[java] view plaincopy
  1. public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {  
  2.        if (mActionBar != null) {  
  3.            return mActionBar.startActionMode(callback);  
  4.        }  
  5.        return null;  
  6.    }  

通过系统给Activity一个控制UI操作模式(Give the Activity a chance to control the UI for an action mode requested by the system.)

[java] view plaincopy
  1. /** 
  2.      * {@inheritDoc} 
  3.      * 
  4.      * Note that if you override this method you should always call through 
  5.      * to the superclass implementation by calling super.onActionModeStarted(mode). 
  6.      */  
  7.     public void onActionModeStarted(ActionMode mode) {  
  8.         mActionMode = mode;  
  9.     }  
  10.   
  11.     /** 
  12.      * {@inheritDoc} 
  13.      * 
  14.      * Note that if you override this method you should always call through 
  15.      * to the superclass implementation by calling super.onActionModeFinished(mode). 
  16.      */  
  17.     public void onActionModeFinished(ActionMode mode) {  
  18.         if (mode == mActionMode) {  
  19.             mActionMode = null;  
  20.         }  
  21.     }  

注意,如果你重写这个方法,你一定要调用父类的super.onActionModeFinished(mode)。开始时候设置mode,结束时把mode设为空。

[java] view plaincopy
  1. /** 
  2.     * @return The activity associated with this dialog, or null if there is no associated activity. 
  3.     */  
  4.    private ComponentName getAssociatedActivity() {  
  5.        Activity activity = mOwnerActivity;  
  6.        Context context = getContext();  
  7.        while (activity == null && context != null) {  
  8.            if (context instanceof Activity) {  
  9.                activity = (Activity) context;  // found it!  
  10.            } else {  
  11.                context = (context instanceof ContextWrapper) ?  
  12.                        ((ContextWrapper) context).getBaseContext() : // unwrap one level  
  13.                        null;                                         // done  
  14.            }  
  15.        }  
  16.        return activity == null ? null : activity.getComponentName();  
  17.    }  

返回相关联activity的名字。

[java] view plaincopy
  1. /** 
  2.      * Request that key events come to this dialog. Use this if your 
  3.      * dialog has no views with focus, but the dialog still wants 
  4.      * a chance to process key events. 
  5.      *  
  6.      * @param get true if the dialog should receive key events, false otherwise 
  7.      * @see android.view.Window#takeKeyEvents 
  8.      */  
  9.     public void takeKeyEvents(boolean get) {  
  10.         mWindow.takeKeyEvents(get);  
  11.     }  

请求来自Dialog的的按键事件,如果dialog上面没有view获取焦点,而且这个dialog想要处理按键事件,就调用该方法。

[java] view plaincopy
  1. /** 
  2.   * Enable extended window features.  This is a convenience for calling 
  3.   * {@link android.view.Window#requestFeature getWindow().requestFeature()}. 
  4.   *  
  5.   * @param featureId The desired feature as defined in 
  6.   *                  {@link android.view.Window}. 
  7.   * @return Returns true if the requested feature is supported and now 
  8.   *         enabled. 
  9.   *  
  10.   * @see android.view.Window#requestFeature 
  11.   */  
  12.  public final boolean requestWindowFeature(int featureId) {  
  13.      return getWindow().requestFeature(featureId);  
  14.  }  

设置window的属性。

[java] view plaincopy
  1. /** 
  2.      * Convenience for calling 
  3.      * {@link android.view.Window#setFeatureDrawableResource}. 
  4.      */  
  5.     public final void setFeatureDrawableResource(int featureId, int resId) {  
  6.         getWindow().setFeatureDrawableResource(featureId, resId);  
  7.     }  
  8.   
  9.     /** 
  10.      * Convenience for calling 
  11.      * {@link android.view.Window#setFeatureDrawableUri}. 
  12.      */  
  13.     public final void setFeatureDrawableUri(int featureId, Uri uri) {  
  14.         getWindow().setFeatureDrawableUri(featureId, uri);  
  15.     }  
  16.   
  17.     /** 
  18.      * Convenience for calling 
  19.      * {@link android.view.Window#setFeatureDrawable(int, Drawable)}. 
  20.      */  
  21.     public final void setFeatureDrawable(int featureId, Drawable drawable) {  
  22.         getWindow().setFeatureDrawable(featureId, drawable);  
  23.     }  
  24.   
  25.     /** 
  26.      * Convenience for calling 
  27.      * {@link android.view.Window#setFeatureDrawableAlpha}. 
  28.      */  
  29.     public final void setFeatureDrawableAlpha(int featureId, int alpha) {  
  30.         getWindow().setFeatureDrawableAlpha(featureId, alpha);  
  31.     }  

设置一系列的drawable特性。

[java] view plaincopy
  1. /** 
  2.   * Sets whether this dialog is cancelable with the 
  3.   * {@link KeyEvent#KEYCODE_BACK BACK} key. 
  4.   */  
  5.  public void setCancelable(boolean flag) {  
  6.      mCancelable = flag;  
  7.  }  

设置dialog是否可以取消。

[java] view plaincopy
  1. /** 
  2.  * Sets whether this dialog is canceled when touched outside the window's 
  3.  * bounds. If setting to true, the dialog is set to be cancelable if not 
  4.  * already set. 
  5.  *  
  6.  * @param cancel Whether the dialog should be canceled when touched outside 
  7.  *            the window. 
  8.  */  
  9. public void setCanceledOnTouchOutside(boolean cancel) {  
  10.     if (cancel && !mCancelable) {  
  11.         mCancelable = true;  
  12.     }  
  13.       
  14.     mWindow.setCloseOnTouchOutside(cancel);  
  15. }  

设置当触摸dialog外部时,dialog是否可以取消。

[java] view plaincopy
  1. /** 
  2.     * Set a listener to be invoked when the dialog is canceled. 
  3.     * <p> 
  4.     * This will only be invoked when the dialog is canceled, if the creator 
  5.     * needs to know when it is dismissed in general, use 
  6.     * {@link #setOnDismissListener}. 
  7.     *  
  8.     * @param listener The {@link DialogInterface.OnCancelListener} to use. 
  9.     */  
  10.    public void setOnCancelListener(final OnCancelListener listener) {  
  11.        if (mCancelAndDismissTaken != null) {  
  12.            throw new IllegalStateException(  
  13.                    "OnCancelListener is already taken by "  
  14.                    + mCancelAndDismissTaken + " and can not be replaced.");  
  15.        }  
  16.        if (listener != null) {  
  17.            mCancelMessage = mListenersHandler.obtainMessage(CANCEL, listener);  
  18.        } else {  
  19.            mCancelMessage = null;  
  20.        }  
  21.    }  

设置一个当dialog被取消时,会被调用的监听。

[java] view plaincopy
  1. /** 
  2.      * Set a message to be sent when the dialog is canceled. 
  3.      * @param msg The msg to send when the dialog is canceled. 
  4.      * @see #setOnCancelListener(android.content.DialogInterface.OnCancelListener) 
  5.      */  
  6.     public void setCancelMessage(final Message msg) {  
  7.         mCancelMessage = msg;  
  8.     }  

当dialog被取消时,设置发送的信息。

[java] view plaincopy
  1. /** 
  2.  * Set a listener to be invoked when the dialog is dismissed. 
  3.  * @param listener The {@link DialogInterface.OnDismissListener} to use. 
  4.  */  
  5. public void setOnDismissListener(final OnDismissListener listener) {  
  6.     if (mCancelAndDismissTaken != null) {  
  7.         throw new IllegalStateException(  
  8.                 "OnDismissListener is already taken by "  
  9.                 + mCancelAndDismissTaken + " and can not be replaced.");  
  10.     }  
  11.     if (listener != null) {  
  12.         mDismissMessage = mListenersHandler.obtainMessage(DISMISS, listener);  
  13.     } else {  
  14.         mDismissMessage = null;  
  15.     }  
  16. }  

设置一个当dialog被销毁时,会被调用的监听

[java] view plaincopy
  1. /** 
  2.   * Sets a listener to be invoked when the dialog is shown. 
  3.   * @param listener The {@link DialogInterface.OnShowListener} to use. 
  4.   */  
  5.  public void setOnShowListener(OnShowListener listener) {  
  6.      if (listener != null) {  
  7.          mShowMessage = mListenersHandler.obtainMessage(SHOW, listener);  
  8.      } else {  
  9.          mShowMessage = null;  
  10.      }  
  11.  }  
设置一个当dialog显示时,会被调用的监听

[java] view plaincopy
  1. /** 
  2.  * Set a message to be sent when the dialog is dismissed. 
  3.  * @param msg The msg to send when the dialog is dismissed. 
  4.  */  
  5. public void setDismissMessage(final Message msg) {  
  6.     mDismissMessage = msg;  
  7. }  

设置dialog被销毁时,发送的信息。

[java] view plaincopy
  1. /** @hide */  
  2.     public boolean takeCancelAndDismissListeners(String msg, final OnCancelListener cancel,  
  3.             final OnDismissListener dismiss) {  
  4.         if (mCancelAndDismissTaken != null) {  
  5.             mCancelAndDismissTaken = null;  
  6.         } else if (mCancelMessage != null || mDismissMessage != null) {  
  7.             return false;  
  8.         }  
  9.           
  10.         setOnCancelListener(cancel);  
  11.         setOnDismissListener(dismiss);  
  12.         mCancelAndDismissTaken = msg;  
  13.           
  14.         return true;  
  15.     }  

同时设置OnCancelListener和OnDismissListener。

[java] view plaincopy
  1. /** 
  2.  * By default, this will use the owner Activity's suggested stream type. 
  3.  *  
  4.  * @see Activity#setVolumeControlStream(int) 
  5.  * @see #setOwnerActivity(Activity) 
  6.  */  
  7. public final void setVolumeControlStream(int streamType) {  
  8.     getWindow().setVolumeControlStream(streamType);  
  9. }  
  10.   
  11. /** 
  12.  * @see Activity#getVolumeControlStream() 
  13.  */  
  14. public final int getVolumeControlStream() {  
  15.     return getWindow().getVolumeControlStream();  
  16. }  


设置和获取Dialog所属的Activity中音量控制键控制的音频流。

[java] view plaincopy
  1. /** 
  2.  * Sets the callback that will be called if a key is dispatched to the dialog. 
  3.  */  
  4. public void setOnKeyListener(final OnKeyListener onKeyListener) {  
  5.     mOnKeyListener = onKeyListener;  
  6. }  

设置一个回调,当按键事件被分发到dialog 回调函数会被调用。

[java] view plaincopy
  1. private static final class ListenersHandler extends Handler {  
  2.         private WeakReference<DialogInterface> mDialog;  
  3.   
  4.         public ListenersHandler(Dialog dialog) {  
  5.             mDialog = new WeakReference<DialogInterface>(dialog);  
  6.         }  
  7.   
  8.         @Override  
  9.         public void handleMessage(Message msg) {  
  10.             switch (msg.what) {  
  11.                 case DISMISS:  
  12.                     ((OnDismissListener) msg.obj).onDismiss(mDialog.get());  
  13.                     break;  
  14.                 case CANCEL:  
  15.                     ((OnCancelListener) msg.obj).onCancel(mDialog.get());  
  16.                     break;  
  17.                 case SHOW:  
  18.                     ((OnShowListener) msg.obj).onShow(mDialog.get());  
  19.                     break;  
  20.             }  
  21.         }  
  22.     }  

ListenersHandler的定义。

0 0