1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.app;
18 
19 import com.android.internal.app.AlertController;
20 
21 import android.annotation.ArrayRes;
22 import android.annotation.AttrRes;
23 import android.annotation.DrawableRes;
24 import android.annotation.StringRes;
25 import android.annotation.StyleRes;
26 import android.content.Context;
27 import android.content.DialogInterface;
28 import android.content.res.ResourceId;
29 import android.database.Cursor;
30 import android.graphics.drawable.Drawable;
31 import android.os.Bundle;
32 import android.os.Message;
33 import android.util.TypedValue;
34 import android.view.ContextThemeWrapper;
35 import android.view.KeyEvent;
36 import android.view.View;
37 import android.view.WindowManager;
38 import android.widget.AdapterView;
39 import android.widget.Button;
40 import android.widget.ListAdapter;
41 import android.widget.ListView;
42 
43 import com.android.internal.R;
44 
45 /**
46  * A subclass of Dialog that can display one, two or three buttons. If you only want to
47  * display a String in this dialog box, use the setMessage() method.  If you
48  * want to display a more complex view, look up the FrameLayout called "custom"
49  * and add your view to it:
50  *
51  * <pre>
52  * FrameLayout fl = findViewById(android.R.id.custom);
53  * fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
54  * </pre>
55  *
56  * <p>The AlertDialog class takes care of automatically setting
57  * {@link WindowManager.LayoutParams#FLAG_ALT_FOCUSABLE_IM
58  * WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM} for you based on whether
59  * any views in the dialog return true from {@link View#onCheckIsTextEditor()
60  * View.onCheckIsTextEditor()}.  Generally you want this set for a Dialog
61  * without text editors, so that it will be placed on top of the current
62  * input method UI.  You can modify this behavior by forcing the flag to your
63  * desired mode after calling {@link #onCreate}.
64  *
65  * <div class="special reference">
66  * <h3>Developer Guides</h3>
67  * <p>For more information about creating dialogs, read the
68  * <a href="{@docRoot}guide/topics/ui/dialogs.html">Dialogs</a> developer guide.</p>
69  * </div>
70  */
71 public class AlertDialog extends Dialog implements DialogInterface {
72     private AlertController mAlert;
73 
74     /**
75      * Special theme constant for {@link #AlertDialog(Context, int)}: use
76      * the traditional (pre-Holo) alert dialog theme.
77      *
78      * @deprecated Use {@link android.R.style#Theme_Material_Dialog_Alert}.
79      */
80     @Deprecated
81     public static final int THEME_TRADITIONAL = 1;
82 
83     /**
84      * Special theme constant for {@link #AlertDialog(Context, int)}: use
85      * the holographic alert theme with a dark background.
86      *
87      * @deprecated Use {@link android.R.style#Theme_Material_Dialog_Alert}.
88      */
89     @Deprecated
90     public static final int THEME_HOLO_DARK = 2;
91 
92     /**
93      * Special theme constant for {@link #AlertDialog(Context, int)}: use
94      * the holographic alert theme with a light background.
95      *
96      * @deprecated Use {@link android.R.style#Theme_Material_Light_Dialog_Alert}.
97      */
98     @Deprecated
99     public static final int THEME_HOLO_LIGHT = 3;
100 
101     /**
102      * Special theme constant for {@link #AlertDialog(Context, int)}: use
103      * the device's default alert theme with a dark background.
104      *
105      * @deprecated Use {@link android.R.style#Theme_DeviceDefault_Dialog_Alert}.
106      */
107     @Deprecated
108     public static final int THEME_DEVICE_DEFAULT_DARK = 4;
109 
110     /**
111      * Special theme constant for {@link #AlertDialog(Context, int)}: use
112      * the device's default alert theme with a light background.
113      *
114      * @deprecated Use {@link android.R.style#Theme_DeviceDefault_Light_Dialog_Alert}.
115      */
116     @Deprecated
117     public static final int THEME_DEVICE_DEFAULT_LIGHT = 5;
118 
119     /**
120      * No layout hint.
121      * @hide
122      */
123     public static final int LAYOUT_HINT_NONE = 0;
124 
125     /**
126      * Hint layout to the side.
127      * @hide
128      */
129     public static final int LAYOUT_HINT_SIDE = 1;
130 
131     /**
132      * Creates an alert dialog that uses the default alert dialog theme.
133      * <p>
134      * The default alert dialog theme is defined by
135      * {@link android.R.attr#alertDialogTheme} within the parent
136      * {@code context}'s theme.
137      *
138      * @param context the parent context
139      * @see android.R.styleable#Theme_alertDialogTheme
140      */
AlertDialog(Context context)141     protected AlertDialog(Context context) {
142         this(context, 0);
143     }
144 
145     /**
146      * Creates an alert dialog that uses the default alert dialog theme and a
147      * custom cancel listener.
148      * <p>
149      * This is functionally identical to:
150      * <pre>
151      *     AlertDialog dialog = new AlertDialog(context);
152      *     alertDialog.setCancelable(cancelable);
153      *     alertDialog.setOnCancelListener(cancelListener);
154      * </pre>
155      * <p>
156      * The default alert dialog theme is defined by
157      * {@link android.R.attr#alertDialogTheme} within the parent
158      * {@code context}'s theme.
159      *
160      * @param context the parent context
161      * @see android.R.styleable#Theme_alertDialogTheme
162      */
AlertDialog(Context context, boolean cancelable, OnCancelListener cancelListener)163     protected AlertDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
164         this(context, 0);
165 
166         setCancelable(cancelable);
167         setOnCancelListener(cancelListener);
168     }
169 
170     /**
171      * Creates an alert dialog that uses an explicit theme resource.
172      * <p>
173      * The specified theme resource ({@code themeResId}) is applied on top of
174      * the parent {@code context}'s theme. It may be specified as a style
175      * resource containing a fully-populated theme, such as
176      * {@link android.R.style#Theme_Material_Dialog}, to replace all attributes
177      * in the parent {@code context}'s theme including primary and accent
178      * colors.
179      * <p>
180      * To preserve attributes such as primary and accent colors, the
181      * {@code themeResId} may instead be specified as an overlay theme such as
182      * {@link android.R.style#ThemeOverlay_Material_Dialog}. This will override
183      * only the window attributes necessary to style the alert window as a
184      * dialog.
185      * <p>
186      * Alternatively, the {@code themeResId} may be specified as {@code 0} to
187      * use the parent {@code context}'s resolved value for
188      * {@link android.R.attr#alertDialogTheme}.
189      *
190      * @param context the parent context
191      * @param themeResId the resource ID of the theme against which to inflate
192      *                   this dialog, or {@code 0} to use the parent
193      *                   {@code context}'s default alert dialog theme
194      * @see android.R.styleable#Theme_alertDialogTheme
195      */
AlertDialog(Context context, @StyleRes int themeResId)196     protected AlertDialog(Context context, @StyleRes int themeResId) {
197         this(context, themeResId, true);
198     }
199 
AlertDialog(Context context, @StyleRes int themeResId, boolean createContextThemeWrapper)200     AlertDialog(Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
201         super(context, createContextThemeWrapper ? resolveDialogTheme(context, themeResId) : 0,
202                 createContextThemeWrapper);
203 
204         mWindow.alwaysReadCloseOnTouchAttr();
205         mAlert = AlertController.create(getContext(), this, getWindow());
206     }
207 
resolveDialogTheme(Context context, @StyleRes int themeResId)208     static @StyleRes int resolveDialogTheme(Context context, @StyleRes int themeResId) {
209         if (themeResId == THEME_TRADITIONAL) {
210             return R.style.Theme_Dialog_Alert;
211         } else if (themeResId == THEME_HOLO_DARK) {
212             return R.style.Theme_Holo_Dialog_Alert;
213         } else if (themeResId == THEME_HOLO_LIGHT) {
214             return R.style.Theme_Holo_Light_Dialog_Alert;
215         } else if (themeResId == THEME_DEVICE_DEFAULT_DARK) {
216             return R.style.Theme_DeviceDefault_Dialog_Alert;
217         } else if (themeResId == THEME_DEVICE_DEFAULT_LIGHT) {
218             return R.style.Theme_DeviceDefault_Light_Dialog_Alert;
219         } else if (ResourceId.isValid(themeResId)) {
220             // start of real resource IDs.
221             return themeResId;
222         } else {
223             final TypedValue outValue = new TypedValue();
224             context.getTheme().resolveAttribute(R.attr.alertDialogTheme, outValue, true);
225             return outValue.resourceId;
226         }
227     }
228 
229     /**
230      * Gets one of the buttons used in the dialog. Returns null if the specified
231      * button does not exist or the dialog has not yet been fully created (for
232      * example, via {@link #show()} or {@link #create()}).
233      *
234      * @param whichButton The identifier of the button that should be returned.
235      *            For example, this can be
236      *            {@link DialogInterface#BUTTON_POSITIVE}.
237      * @return The button from the dialog, or null if a button does not exist.
238      */
getButton(int whichButton)239     public Button getButton(int whichButton) {
240         return mAlert.getButton(whichButton);
241     }
242 
243     /**
244      * Gets the list view used in the dialog.
245      *
246      * @return The {@link ListView} from the dialog.
247      */
getListView()248     public ListView getListView() {
249         return mAlert.getListView();
250     }
251 
252     @Override
setTitle(CharSequence title)253     public void setTitle(CharSequence title) {
254         super.setTitle(title);
255         mAlert.setTitle(title);
256     }
257 
258     /**
259      * @see Builder#setCustomTitle(View)
260      */
setCustomTitle(View customTitleView)261     public void setCustomTitle(View customTitleView) {
262         mAlert.setCustomTitle(customTitleView);
263     }
264 
setMessage(CharSequence message)265     public void setMessage(CharSequence message) {
266         mAlert.setMessage(message);
267     }
268 
269     /**
270      * Set the view to display in that dialog.
271      */
setView(View view)272     public void setView(View view) {
273         mAlert.setView(view);
274     }
275 
276     /**
277      * Set the view to display in that dialog, specifying the spacing to appear around that
278      * view.
279      *
280      * @param view The view to show in the content area of the dialog
281      * @param viewSpacingLeft Extra space to appear to the left of {@code view}
282      * @param viewSpacingTop Extra space to appear above {@code view}
283      * @param viewSpacingRight Extra space to appear to the right of {@code view}
284      * @param viewSpacingBottom Extra space to appear below {@code view}
285      */
setView(View view, int viewSpacingLeft, int viewSpacingTop, int viewSpacingRight, int viewSpacingBottom)286     public void setView(View view, int viewSpacingLeft, int viewSpacingTop, int viewSpacingRight,
287             int viewSpacingBottom) {
288         mAlert.setView(view, viewSpacingLeft, viewSpacingTop, viewSpacingRight, viewSpacingBottom);
289     }
290 
291     /**
292      * Internal api to allow hinting for the best button panel layout.
293      * @hide
294      */
setButtonPanelLayoutHint(int layoutHint)295     void setButtonPanelLayoutHint(int layoutHint) {
296         mAlert.setButtonPanelLayoutHint(layoutHint);
297     }
298 
299     /**
300      * Set a message to be sent when a button is pressed.
301      *
302      * @param whichButton Which button to set the message for, can be one of
303      *            {@link DialogInterface#BUTTON_POSITIVE},
304      *            {@link DialogInterface#BUTTON_NEGATIVE}, or
305      *            {@link DialogInterface#BUTTON_NEUTRAL}
306      * @param text The text to display in positive button.
307      * @param msg The {@link Message} to be sent when clicked.
308      */
setButton(int whichButton, CharSequence text, Message msg)309     public void setButton(int whichButton, CharSequence text, Message msg) {
310         mAlert.setButton(whichButton, text, null, msg);
311     }
312 
313     /**
314      * Set a listener to be invoked when the positive button of the dialog is pressed.
315      *
316      * @param whichButton Which button to set the listener on, can be one of
317      *            {@link DialogInterface#BUTTON_POSITIVE},
318      *            {@link DialogInterface#BUTTON_NEGATIVE}, or
319      *            {@link DialogInterface#BUTTON_NEUTRAL}
320      * @param text The text to display in positive button.
321      * @param listener The {@link DialogInterface.OnClickListener} to use.
322      */
setButton(int whichButton, CharSequence text, OnClickListener listener)323     public void setButton(int whichButton, CharSequence text, OnClickListener listener) {
324         mAlert.setButton(whichButton, text, listener, null);
325     }
326 
327     /**
328      * @deprecated Use {@link #setButton(int, CharSequence, Message)} with
329      *             {@link DialogInterface#BUTTON_POSITIVE}.
330      */
331     @Deprecated
setButton(CharSequence text, Message msg)332     public void setButton(CharSequence text, Message msg) {
333         setButton(BUTTON_POSITIVE, text, msg);
334     }
335 
336     /**
337      * @deprecated Use {@link #setButton(int, CharSequence, Message)} with
338      *             {@link DialogInterface#BUTTON_NEGATIVE}.
339      */
340     @Deprecated
setButton2(CharSequence text, Message msg)341     public void setButton2(CharSequence text, Message msg) {
342         setButton(BUTTON_NEGATIVE, text, msg);
343     }
344 
345     /**
346      * @deprecated Use {@link #setButton(int, CharSequence, Message)} with
347      *             {@link DialogInterface#BUTTON_NEUTRAL}.
348      */
349     @Deprecated
setButton3(CharSequence text, Message msg)350     public void setButton3(CharSequence text, Message msg) {
351         setButton(BUTTON_NEUTRAL, text, msg);
352     }
353 
354     /**
355      * Set a listener to be invoked when button 1 of the dialog is pressed.
356      *
357      * @param text The text to display in button 1.
358      * @param listener The {@link DialogInterface.OnClickListener} to use.
359      * @deprecated Use
360      *             {@link #setButton(int, CharSequence, android.content.DialogInterface.OnClickListener)}
361      *             with {@link DialogInterface#BUTTON_POSITIVE}
362      */
363     @Deprecated
setButton(CharSequence text, final OnClickListener listener)364     public void setButton(CharSequence text, final OnClickListener listener) {
365         setButton(BUTTON_POSITIVE, text, listener);
366     }
367 
368     /**
369      * Set a listener to be invoked when button 2 of the dialog is pressed.
370      * @param text The text to display in button 2.
371      * @param listener The {@link DialogInterface.OnClickListener} to use.
372      * @deprecated Use
373      *             {@link #setButton(int, CharSequence, android.content.DialogInterface.OnClickListener)}
374      *             with {@link DialogInterface#BUTTON_NEGATIVE}
375      */
376     @Deprecated
setButton2(CharSequence text, final OnClickListener listener)377     public void setButton2(CharSequence text, final OnClickListener listener) {
378         setButton(BUTTON_NEGATIVE, text, listener);
379     }
380 
381     /**
382      * Set a listener to be invoked when button 3 of the dialog is pressed.
383      * @param text The text to display in button 3.
384      * @param listener The {@link DialogInterface.OnClickListener} to use.
385      * @deprecated Use
386      *             {@link #setButton(int, CharSequence, android.content.DialogInterface.OnClickListener)}
387      *             with {@link DialogInterface#BUTTON_POSITIVE}
388      */
389     @Deprecated
setButton3(CharSequence text, final OnClickListener listener)390     public void setButton3(CharSequence text, final OnClickListener listener) {
391         setButton(BUTTON_NEUTRAL, text, listener);
392     }
393 
394     /**
395      * Set resId to 0 if you don't want an icon.
396      * @param resId the resourceId of the drawable to use as the icon or 0
397      * if you don't want an icon.
398      */
setIcon(@rawableRes int resId)399     public void setIcon(@DrawableRes int resId) {
400         mAlert.setIcon(resId);
401     }
402 
setIcon(Drawable icon)403     public void setIcon(Drawable icon) {
404         mAlert.setIcon(icon);
405     }
406 
407     /**
408      * Set an icon as supplied by a theme attribute. e.g. android.R.attr.alertDialogIcon
409      *
410      * @param attrId ID of a theme attribute that points to a drawable resource.
411      */
setIconAttribute(@ttrRes int attrId)412     public void setIconAttribute(@AttrRes int attrId) {
413         TypedValue out = new TypedValue();
414         mContext.getTheme().resolveAttribute(attrId, out, true);
415         mAlert.setIcon(out.resourceId);
416     }
417 
setInverseBackgroundForced(boolean forceInverseBackground)418     public void setInverseBackgroundForced(boolean forceInverseBackground) {
419         mAlert.setInverseBackgroundForced(forceInverseBackground);
420     }
421 
422     @Override
onCreate(Bundle savedInstanceState)423     protected void onCreate(Bundle savedInstanceState) {
424         super.onCreate(savedInstanceState);
425         mAlert.installContent();
426     }
427 
428     @Override
onKeyDown(int keyCode, KeyEvent event)429     public boolean onKeyDown(int keyCode, KeyEvent event) {
430         if (mAlert.onKeyDown(keyCode, event)) return true;
431         return super.onKeyDown(keyCode, event);
432     }
433 
434     @Override
onKeyUp(int keyCode, KeyEvent event)435     public boolean onKeyUp(int keyCode, KeyEvent event) {
436         if (mAlert.onKeyUp(keyCode, event)) return true;
437         return super.onKeyUp(keyCode, event);
438     }
439 
440     public static class Builder {
441         private final AlertController.AlertParams P;
442 
443         /**
444          * Creates a builder for an alert dialog that uses the default alert
445          * dialog theme.
446          * <p>
447          * The default alert dialog theme is defined by
448          * {@link android.R.attr#alertDialogTheme} within the parent
449          * {@code context}'s theme.
450          *
451          * @param context the parent context
452          */
Builder(Context context)453         public Builder(Context context) {
454             this(context, resolveDialogTheme(context, ResourceId.ID_NULL));
455         }
456 
457         /**
458          * Creates a builder for an alert dialog that uses an explicit theme
459          * resource.
460          * <p>
461          * The specified theme resource ({@code themeResId}) is applied on top
462          * of the parent {@code context}'s theme. It may be specified as a
463          * style resource containing a fully-populated theme, such as
464          * {@link android.R.style#Theme_Material_Dialog}, to replace all
465          * attributes in the parent {@code context}'s theme including primary
466          * and accent colors.
467          * <p>
468          * To preserve attributes such as primary and accent colors, the
469          * {@code themeResId} may instead be specified as an overlay theme such
470          * as {@link android.R.style#ThemeOverlay_Material_Dialog}. This will
471          * override only the window attributes necessary to style the alert
472          * window as a dialog.
473          * <p>
474          * Alternatively, the {@code themeResId} may be specified as {@code 0}
475          * to use the parent {@code context}'s resolved value for
476          * {@link android.R.attr#alertDialogTheme}.
477          *
478          * @param context the parent context
479          * @param themeResId the resource ID of the theme against which to inflate
480          *                   this dialog, or {@code 0} to use the parent
481          *                   {@code context}'s default alert dialog theme
482          */
Builder(Context context, int themeResId)483         public Builder(Context context, int themeResId) {
484             P = new AlertController.AlertParams(new ContextThemeWrapper(
485                     context, resolveDialogTheme(context, themeResId)));
486         }
487 
488         /**
489          * Returns a {@link Context} with the appropriate theme for dialogs created by this Builder.
490          * Applications should use this Context for obtaining LayoutInflaters for inflating views
491          * that will be used in the resulting dialogs, as it will cause views to be inflated with
492          * the correct theme.
493          *
494          * @return A Context for built Dialogs.
495          */
getContext()496         public Context getContext() {
497             return P.mContext;
498         }
499 
500         /**
501          * Set the title using the given resource id.
502          *
503          * @return This Builder object to allow for chaining of calls to set methods
504          */
setTitle(@tringRes int titleId)505         public Builder setTitle(@StringRes int titleId) {
506             P.mTitle = P.mContext.getText(titleId);
507             return this;
508         }
509 
510         /**
511          * Set the title displayed in the {@link Dialog}.
512          *
513          * @return This Builder object to allow for chaining of calls to set methods
514          */
setTitle(CharSequence title)515         public Builder setTitle(CharSequence title) {
516             P.mTitle = title;
517             return this;
518         }
519 
520         /**
521          * Set the title using the custom view {@code customTitleView}.
522          * <p>
523          * The methods {@link #setTitle(int)} and {@link #setIcon(int)} should
524          * be sufficient for most titles, but this is provided if the title
525          * needs more customization. Using this will replace the title and icon
526          * set via the other methods.
527          * <p>
528          * <strong>Note:</strong> To ensure consistent styling, the custom view
529          * should be inflated or constructed using the alert dialog's themed
530          * context obtained via {@link #getContext()}.
531          *
532          * @param customTitleView the custom view to use as the title
533          * @return this Builder object to allow for chaining of calls to set
534          *         methods
535          */
setCustomTitle(View customTitleView)536         public Builder setCustomTitle(View customTitleView) {
537             P.mCustomTitleView = customTitleView;
538             return this;
539         }
540 
541         /**
542          * Set the message to display using the given resource id.
543          *
544          * @return This Builder object to allow for chaining of calls to set methods
545          */
setMessage(@tringRes int messageId)546         public Builder setMessage(@StringRes int messageId) {
547             P.mMessage = P.mContext.getText(messageId);
548             return this;
549         }
550 
551         /**
552          * Set the message to display.
553           *
554          * @return This Builder object to allow for chaining of calls to set methods
555          */
setMessage(CharSequence message)556         public Builder setMessage(CharSequence message) {
557             P.mMessage = message;
558             return this;
559         }
560 
561         /**
562          * Set the resource id of the {@link Drawable} to be used in the title.
563          * <p>
564          * Takes precedence over values set using {@link #setIcon(Drawable)}.
565          *
566          * @return This Builder object to allow for chaining of calls to set methods
567          */
setIcon(@rawableRes int iconId)568         public Builder setIcon(@DrawableRes int iconId) {
569             P.mIconId = iconId;
570             return this;
571         }
572 
573         /**
574          * Set the {@link Drawable} to be used in the title.
575          * <p>
576          * <strong>Note:</strong> To ensure consistent styling, the drawable
577          * should be inflated or constructed using the alert dialog's themed
578          * context obtained via {@link #getContext()}.
579          *
580          * @return this Builder object to allow for chaining of calls to set
581          *         methods
582          */
setIcon(Drawable icon)583         public Builder setIcon(Drawable icon) {
584             P.mIcon = icon;
585             return this;
586         }
587 
588         /**
589          * Set an icon as supplied by a theme attribute. e.g.
590          * {@link android.R.attr#alertDialogIcon}.
591          * <p>
592          * Takes precedence over values set using {@link #setIcon(int)} or
593          * {@link #setIcon(Drawable)}.
594          *
595          * @param attrId ID of a theme attribute that points to a drawable resource.
596          */
setIconAttribute(@ttrRes int attrId)597         public Builder setIconAttribute(@AttrRes int attrId) {
598             TypedValue out = new TypedValue();
599             P.mContext.getTheme().resolveAttribute(attrId, out, true);
600             P.mIconId = out.resourceId;
601             return this;
602         }
603 
604         /**
605          * Set a listener to be invoked when the positive button of the dialog is pressed.
606          * @param textId The resource id of the text to display in the positive button
607          * @param listener The {@link DialogInterface.OnClickListener} to use.
608          *
609          * @return This Builder object to allow for chaining of calls to set methods
610          */
setPositiveButton(@tringRes int textId, final OnClickListener listener)611         public Builder setPositiveButton(@StringRes int textId, final OnClickListener listener) {
612             P.mPositiveButtonText = P.mContext.getText(textId);
613             P.mPositiveButtonListener = listener;
614             return this;
615         }
616 
617         /**
618          * Set a listener to be invoked when the positive button of the dialog is pressed.
619          * @param text The text to display in the positive button
620          * @param listener The {@link DialogInterface.OnClickListener} to use.
621          *
622          * @return This Builder object to allow for chaining of calls to set methods
623          */
setPositiveButton(CharSequence text, final OnClickListener listener)624         public Builder setPositiveButton(CharSequence text, final OnClickListener listener) {
625             P.mPositiveButtonText = text;
626             P.mPositiveButtonListener = listener;
627             return this;
628         }
629 
630         /**
631          * Set a listener to be invoked when the negative button of the dialog is pressed.
632          * @param textId The resource id of the text to display in the negative button
633          * @param listener The {@link DialogInterface.OnClickListener} to use.
634          *
635          * @return This Builder object to allow for chaining of calls to set methods
636          */
setNegativeButton(@tringRes int textId, final OnClickListener listener)637         public Builder setNegativeButton(@StringRes int textId, final OnClickListener listener) {
638             P.mNegativeButtonText = P.mContext.getText(textId);
639             P.mNegativeButtonListener = listener;
640             return this;
641         }
642 
643         /**
644          * Set a listener to be invoked when the negative button of the dialog is pressed.
645          * @param text The text to display in the negative button
646          * @param listener The {@link DialogInterface.OnClickListener} to use.
647          *
648          * @return This Builder object to allow for chaining of calls to set methods
649          */
setNegativeButton(CharSequence text, final OnClickListener listener)650         public Builder setNegativeButton(CharSequence text, final OnClickListener listener) {
651             P.mNegativeButtonText = text;
652             P.mNegativeButtonListener = listener;
653             return this;
654         }
655 
656         /**
657          * Set a listener to be invoked when the neutral button of the dialog is pressed.
658          * @param textId The resource id of the text to display in the neutral button
659          * @param listener The {@link DialogInterface.OnClickListener} to use.
660          *
661          * @return This Builder object to allow for chaining of calls to set methods
662          */
setNeutralButton(@tringRes int textId, final OnClickListener listener)663         public Builder setNeutralButton(@StringRes int textId, final OnClickListener listener) {
664             P.mNeutralButtonText = P.mContext.getText(textId);
665             P.mNeutralButtonListener = listener;
666             return this;
667         }
668 
669         /**
670          * Set a listener to be invoked when the neutral button of the dialog is pressed.
671          * @param text The text to display in the neutral button
672          * @param listener The {@link DialogInterface.OnClickListener} to use.
673          *
674          * @return This Builder object to allow for chaining of calls to set methods
675          */
setNeutralButton(CharSequence text, final OnClickListener listener)676         public Builder setNeutralButton(CharSequence text, final OnClickListener listener) {
677             P.mNeutralButtonText = text;
678             P.mNeutralButtonListener = listener;
679             return this;
680         }
681 
682         /**
683          * Sets whether the dialog is cancelable or not.  Default is true.
684          *
685          * @return This Builder object to allow for chaining of calls to set methods
686          */
setCancelable(boolean cancelable)687         public Builder setCancelable(boolean cancelable) {
688             P.mCancelable = cancelable;
689             return this;
690         }
691 
692         /**
693          * Sets the callback that will be called if the dialog is canceled.
694          *
695          * <p>Even in a cancelable dialog, the dialog may be dismissed for reasons other than
696          * being canceled or one of the supplied choices being selected.
697          * If you are interested in listening for all cases where the dialog is dismissed
698          * and not just when it is canceled, see
699          * {@link #setOnDismissListener(android.content.DialogInterface.OnDismissListener) setOnDismissListener}.</p>
700          * @see #setCancelable(boolean)
701          * @see #setOnDismissListener(android.content.DialogInterface.OnDismissListener)
702          *
703          * @return This Builder object to allow for chaining of calls to set methods
704          */
setOnCancelListener(OnCancelListener onCancelListener)705         public Builder setOnCancelListener(OnCancelListener onCancelListener) {
706             P.mOnCancelListener = onCancelListener;
707             return this;
708         }
709 
710         /**
711          * Sets the callback that will be called when the dialog is dismissed for any reason.
712          *
713          * @return This Builder object to allow for chaining of calls to set methods
714          */
setOnDismissListener(OnDismissListener onDismissListener)715         public Builder setOnDismissListener(OnDismissListener onDismissListener) {
716             P.mOnDismissListener = onDismissListener;
717             return this;
718         }
719 
720         /**
721          * Sets the callback that will be called if a key is dispatched to the dialog.
722          *
723          * @return This Builder object to allow for chaining of calls to set methods
724          */
setOnKeyListener(OnKeyListener onKeyListener)725         public Builder setOnKeyListener(OnKeyListener onKeyListener) {
726             P.mOnKeyListener = onKeyListener;
727             return this;
728         }
729 
730         /**
731          * Set a list of items to be displayed in the dialog as the content, you will be notified of the
732          * selected item via the supplied listener. This should be an array type i.e. R.array.foo
733          *
734          * @return This Builder object to allow for chaining of calls to set methods
735          */
setItems(@rrayRes int itemsId, final OnClickListener listener)736         public Builder setItems(@ArrayRes int itemsId, final OnClickListener listener) {
737             P.mItems = P.mContext.getResources().getTextArray(itemsId);
738             P.mOnClickListener = listener;
739             return this;
740         }
741 
742         /**
743          * Set a list of items to be displayed in the dialog as the content, you will be notified of the
744          * selected item via the supplied listener.
745          *
746          * @return This Builder object to allow for chaining of calls to set methods
747          */
setItems(CharSequence[] items, final OnClickListener listener)748         public Builder setItems(CharSequence[] items, final OnClickListener listener) {
749             P.mItems = items;
750             P.mOnClickListener = listener;
751             return this;
752         }
753 
754         /**
755          * Set a list of items, which are supplied by the given {@link ListAdapter}, to be
756          * displayed in the dialog as the content, you will be notified of the
757          * selected item via the supplied listener.
758          *
759          * @param adapter The {@link ListAdapter} to supply the list of items
760          * @param listener The listener that will be called when an item is clicked.
761          *
762          * @return This Builder object to allow for chaining of calls to set methods
763          */
setAdapter(final ListAdapter adapter, final OnClickListener listener)764         public Builder setAdapter(final ListAdapter adapter, final OnClickListener listener) {
765             P.mAdapter = adapter;
766             P.mOnClickListener = listener;
767             return this;
768         }
769 
770         /**
771          * Set a list of items, which are supplied by the given {@link Cursor}, to be
772          * displayed in the dialog as the content, you will be notified of the
773          * selected item via the supplied listener.
774          *
775          * @param cursor The {@link Cursor} to supply the list of items
776          * @param listener The listener that will be called when an item is clicked.
777          * @param labelColumn The column name on the cursor containing the string to display
778          *          in the label.
779          *
780          * @return This Builder object to allow for chaining of calls to set methods
781          */
setCursor(final Cursor cursor, final OnClickListener listener, String labelColumn)782         public Builder setCursor(final Cursor cursor, final OnClickListener listener,
783                 String labelColumn) {
784             P.mCursor = cursor;
785             P.mLabelColumn = labelColumn;
786             P.mOnClickListener = listener;
787             return this;
788         }
789 
790         /**
791          * Set a list of items to be displayed in the dialog as the content,
792          * you will be notified of the selected item via the supplied listener.
793          * This should be an array type, e.g. R.array.foo. The list will have
794          * a check mark displayed to the right of the text for each checked
795          * item. Clicking on an item in the list will not dismiss the dialog.
796          * Clicking on a button will dismiss the dialog.
797          *
798          * @param itemsId the resource id of an array i.e. R.array.foo
799          * @param checkedItems specifies which items are checked. It should be null in which case no
800          *        items are checked. If non null it must be exactly the same length as the array of
801          *        items.
802          * @param listener notified when an item on the list is clicked. The dialog will not be
803          *        dismissed when an item is clicked. It will only be dismissed if clicked on a
804          *        button, if no buttons are supplied it's up to the user to dismiss the dialog.
805          *
806          * @return This Builder object to allow for chaining of calls to set methods
807          */
setMultiChoiceItems(@rrayRes int itemsId, boolean[] checkedItems, final OnMultiChoiceClickListener listener)808         public Builder setMultiChoiceItems(@ArrayRes int itemsId, boolean[] checkedItems,
809                 final OnMultiChoiceClickListener listener) {
810             P.mItems = P.mContext.getResources().getTextArray(itemsId);
811             P.mOnCheckboxClickListener = listener;
812             P.mCheckedItems = checkedItems;
813             P.mIsMultiChoice = true;
814             return this;
815         }
816 
817         /**
818          * Set a list of items to be displayed in the dialog as the content,
819          * you will be notified of the selected item via the supplied listener.
820          * The list will have a check mark displayed to the right of the text
821          * for each checked item. Clicking on an item in the list will not
822          * dismiss the dialog. Clicking on a button will dismiss the dialog.
823          *
824          * @param items the text of the items to be displayed in the list.
825          * @param checkedItems specifies which items are checked. It should be null in which case no
826          *        items are checked. If non null it must be exactly the same length as the array of
827          *        items.
828          * @param listener notified when an item on the list is clicked. The dialog will not be
829          *        dismissed when an item is clicked. It will only be dismissed if clicked on a
830          *        button, if no buttons are supplied it's up to the user to dismiss the dialog.
831          *
832          * @return This Builder object to allow for chaining of calls to set methods
833          */
setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, final OnMultiChoiceClickListener listener)834         public Builder setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems,
835                 final OnMultiChoiceClickListener listener) {
836             P.mItems = items;
837             P.mOnCheckboxClickListener = listener;
838             P.mCheckedItems = checkedItems;
839             P.mIsMultiChoice = true;
840             return this;
841         }
842 
843         /**
844          * Set a list of items to be displayed in the dialog as the content,
845          * you will be notified of the selected item via the supplied listener.
846          * The list will have a check mark displayed to the right of the text
847          * for each checked item. Clicking on an item in the list will not
848          * dismiss the dialog. Clicking on a button will dismiss the dialog.
849          *
850          * @param cursor the cursor used to provide the items.
851          * @param isCheckedColumn specifies the column name on the cursor to use to determine
852          *        whether a checkbox is checked or not. It must return an integer value where 1
853          *        means checked and 0 means unchecked.
854          * @param labelColumn The column name on the cursor containing the string to display in the
855          *        label.
856          * @param listener notified when an item on the list is clicked. The dialog will not be
857          *        dismissed when an item is clicked. It will only be dismissed if clicked on a
858          *        button, if no buttons are supplied it's up to the user to dismiss the dialog.
859          *
860          * @return This Builder object to allow for chaining of calls to set methods
861          */
setMultiChoiceItems(Cursor cursor, String isCheckedColumn, String labelColumn, final OnMultiChoiceClickListener listener)862         public Builder setMultiChoiceItems(Cursor cursor, String isCheckedColumn, String labelColumn,
863                 final OnMultiChoiceClickListener listener) {
864             P.mCursor = cursor;
865             P.mOnCheckboxClickListener = listener;
866             P.mIsCheckedColumn = isCheckedColumn;
867             P.mLabelColumn = labelColumn;
868             P.mIsMultiChoice = true;
869             return this;
870         }
871 
872         /**
873          * Set a list of items to be displayed in the dialog as the content, you will be notified of
874          * the selected item via the supplied listener. This should be an array type i.e.
875          * R.array.foo The list will have a check mark displayed to the right of the text for the
876          * checked item. Clicking on an item in the list will not dismiss the dialog. Clicking on a
877          * button will dismiss the dialog.
878          *
879          * @param itemsId the resource id of an array i.e. R.array.foo
880          * @param checkedItem specifies which item is checked. If -1 no items are checked.
881          * @param listener notified when an item on the list is clicked. The dialog will not be
882          *        dismissed when an item is clicked. It will only be dismissed if clicked on a
883          *        button, if no buttons are supplied it's up to the user to dismiss the dialog.
884          *
885          * @return This Builder object to allow for chaining of calls to set methods
886          */
setSingleChoiceItems(@rrayRes int itemsId, int checkedItem, final OnClickListener listener)887         public Builder setSingleChoiceItems(@ArrayRes int itemsId, int checkedItem,
888                 final OnClickListener listener) {
889             P.mItems = P.mContext.getResources().getTextArray(itemsId);
890             P.mOnClickListener = listener;
891             P.mCheckedItem = checkedItem;
892             P.mIsSingleChoice = true;
893             return this;
894         }
895 
896         /**
897          * Set a list of items to be displayed in the dialog as the content, you will be notified of
898          * the selected item via the supplied listener. The list will have a check mark displayed to
899          * the right of the text for the checked item. Clicking on an item in the list will not
900          * dismiss the dialog. Clicking on a button will dismiss the dialog.
901          *
902          * @param cursor the cursor to retrieve the items from.
903          * @param checkedItem specifies which item is checked. If -1 no items are checked.
904          * @param labelColumn The column name on the cursor containing the string to display in the
905          *        label.
906          * @param listener notified when an item on the list is clicked. The dialog will not be
907          *        dismissed when an item is clicked. It will only be dismissed if clicked on a
908          *        button, if no buttons are supplied it's up to the user to dismiss the dialog.
909          *
910          * @return This Builder object to allow for chaining of calls to set methods
911          */
setSingleChoiceItems(Cursor cursor, int checkedItem, String labelColumn, final OnClickListener listener)912         public Builder setSingleChoiceItems(Cursor cursor, int checkedItem, String labelColumn,
913                 final OnClickListener listener) {
914             P.mCursor = cursor;
915             P.mOnClickListener = listener;
916             P.mCheckedItem = checkedItem;
917             P.mLabelColumn = labelColumn;
918             P.mIsSingleChoice = true;
919             return this;
920         }
921 
922         /**
923          * Set a list of items to be displayed in the dialog as the content, you will be notified of
924          * the selected item via the supplied listener. The list will have a check mark displayed to
925          * the right of the text for the checked item. Clicking on an item in the list will not
926          * dismiss the dialog. Clicking on a button will dismiss the dialog.
927          *
928          * @param items the items to be displayed.
929          * @param checkedItem specifies which item is checked. If -1 no items are checked.
930          * @param listener notified when an item on the list is clicked. The dialog will not be
931          *        dismissed when an item is clicked. It will only be dismissed if clicked on a
932          *        button, if no buttons are supplied it's up to the user to dismiss the dialog.
933          *
934          * @return This Builder object to allow for chaining of calls to set methods
935          */
setSingleChoiceItems(CharSequence[] items, int checkedItem, final OnClickListener listener)936         public Builder setSingleChoiceItems(CharSequence[] items, int checkedItem, final OnClickListener listener) {
937             P.mItems = items;
938             P.mOnClickListener = listener;
939             P.mCheckedItem = checkedItem;
940             P.mIsSingleChoice = true;
941             return this;
942         }
943 
944         /**
945          * Set a list of items to be displayed in the dialog as the content, you will be notified of
946          * the selected item via the supplied listener. The list will have a check mark displayed to
947          * the right of the text for the checked item. Clicking on an item in the list will not
948          * dismiss the dialog. Clicking on a button will dismiss the dialog.
949          *
950          * @param adapter The {@link ListAdapter} to supply the list of items
951          * @param checkedItem specifies which item is checked. If -1 no items are checked.
952          * @param listener notified when an item on the list is clicked. The dialog will not be
953          *        dismissed when an item is clicked. It will only be dismissed if clicked on a
954          *        button, if no buttons are supplied it's up to the user to dismiss the dialog.
955          *
956          * @return This Builder object to allow for chaining of calls to set methods
957          */
setSingleChoiceItems(ListAdapter adapter, int checkedItem, final OnClickListener listener)958         public Builder setSingleChoiceItems(ListAdapter adapter, int checkedItem, final OnClickListener listener) {
959             P.mAdapter = adapter;
960             P.mOnClickListener = listener;
961             P.mCheckedItem = checkedItem;
962             P.mIsSingleChoice = true;
963             return this;
964         }
965 
966         /**
967          * Sets a listener to be invoked when an item in the list is selected.
968          *
969          * @param listener the listener to be invoked
970          * @return this Builder object to allow for chaining of calls to set methods
971          * @see AdapterView#setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener)
972          */
setOnItemSelectedListener(final AdapterView.OnItemSelectedListener listener)973         public Builder setOnItemSelectedListener(final AdapterView.OnItemSelectedListener listener) {
974             P.mOnItemSelectedListener = listener;
975             return this;
976         }
977 
978         /**
979          * Set a custom view resource to be the contents of the Dialog. The
980          * resource will be inflated, adding all top-level views to the screen.
981          *
982          * @param layoutResId Resource ID to be inflated.
983          * @return this Builder object to allow for chaining of calls to set
984          *         methods
985          */
setView(int layoutResId)986         public Builder setView(int layoutResId) {
987             P.mView = null;
988             P.mViewLayoutResId = layoutResId;
989             P.mViewSpacingSpecified = false;
990             return this;
991         }
992 
993         /**
994          * Sets a custom view to be the contents of the alert dialog.
995          * <p>
996          * When using a pre-Holo theme, if the supplied view is an instance of
997          * a {@link ListView} then the light background will be used.
998          * <p>
999          * <strong>Note:</strong> To ensure consistent styling, the custom view
1000          * should be inflated or constructed using the alert dialog's themed
1001          * context obtained via {@link #getContext()}.
1002          *
1003          * @param view the view to use as the contents of the alert dialog
1004          * @return this Builder object to allow for chaining of calls to set
1005          *         methods
1006          */
setView(View view)1007         public Builder setView(View view) {
1008             P.mView = view;
1009             P.mViewLayoutResId = 0;
1010             P.mViewSpacingSpecified = false;
1011             return this;
1012         }
1013 
1014         /**
1015          * Sets a custom view to be the contents of the alert dialog and
1016          * specifies additional padding around that view.
1017          * <p>
1018          * When using a pre-Holo theme, if the supplied view is an instance of
1019          * a {@link ListView} then the light background will be used.
1020          * <p>
1021          * <strong>Note:</strong> To ensure consistent styling, the custom view
1022          * should be inflated or constructed using the alert dialog's themed
1023          * context obtained via {@link #getContext()}.
1024          *
1025          * @param view the view to use as the contents of the alert dialog
1026          * @param viewSpacingLeft spacing between the left edge of the view and
1027          *                        the dialog frame
1028          * @param viewSpacingTop spacing between the top edge of the view and
1029          *                       the dialog frame
1030          * @param viewSpacingRight spacing between the right edge of the view
1031          *                         and the dialog frame
1032          * @param viewSpacingBottom spacing between the bottom edge of the view
1033          *                          and the dialog frame
1034          * @return this Builder object to allow for chaining of calls to set
1035          *         methods
1036          *
1037          * @hide Remove once the framework usages have been replaced.
1038          * @deprecated Set the padding on the view itself.
1039          */
1040         @Deprecated
setView(View view, int viewSpacingLeft, int viewSpacingTop, int viewSpacingRight, int viewSpacingBottom)1041         public Builder setView(View view, int viewSpacingLeft, int viewSpacingTop,
1042                 int viewSpacingRight, int viewSpacingBottom) {
1043             P.mView = view;
1044             P.mViewLayoutResId = 0;
1045             P.mViewSpacingSpecified = true;
1046             P.mViewSpacingLeft = viewSpacingLeft;
1047             P.mViewSpacingTop = viewSpacingTop;
1048             P.mViewSpacingRight = viewSpacingRight;
1049             P.mViewSpacingBottom = viewSpacingBottom;
1050             return this;
1051         }
1052 
1053         /**
1054          * Sets the alert dialog to use the inverse background, regardless of
1055          * what the contents is.
1056          *
1057          * @param useInverseBackground whether to use the inverse background
1058          * @return this Builder object to allow for chaining of calls to set methods
1059          * @deprecated This flag is only used for pre-Material themes. Instead,
1060          *             specify the window background using on the alert dialog
1061          *             theme.
1062          */
1063         @Deprecated
setInverseBackgroundForced(boolean useInverseBackground)1064         public Builder setInverseBackgroundForced(boolean useInverseBackground) {
1065             P.mForceInverseBackground = useInverseBackground;
1066             return this;
1067         }
1068 
1069         /**
1070          * @hide
1071          */
setRecycleOnMeasureEnabled(boolean enabled)1072         public Builder setRecycleOnMeasureEnabled(boolean enabled) {
1073             P.mRecycleOnMeasure = enabled;
1074             return this;
1075         }
1076 
1077 
1078         /**
1079          * Creates an {@link AlertDialog} with the arguments supplied to this
1080          * builder.
1081          * <p>
1082          * Calling this method does not display the dialog. If no additional
1083          * processing is needed, {@link #show()} may be called instead to both
1084          * create and display the dialog.
1085          */
create()1086         public AlertDialog create() {
1087             // Context has already been wrapped with the appropriate theme.
1088             final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);
1089             P.apply(dialog.mAlert);
1090             dialog.setCancelable(P.mCancelable);
1091             if (P.mCancelable) {
1092                 dialog.setCanceledOnTouchOutside(true);
1093             }
1094             dialog.setOnCancelListener(P.mOnCancelListener);
1095             dialog.setOnDismissListener(P.mOnDismissListener);
1096             if (P.mOnKeyListener != null) {
1097                 dialog.setOnKeyListener(P.mOnKeyListener);
1098             }
1099             return dialog;
1100         }
1101 
1102         /**
1103          * Creates an {@link AlertDialog} with the arguments supplied to this
1104          * builder and immediately displays the dialog.
1105          * <p>
1106          * Calling this method is functionally identical to:
1107          * <pre>
1108          *     AlertDialog dialog = builder.create();
1109          *     dialog.show();
1110          * </pre>
1111          */
show()1112         public AlertDialog show() {
1113             final AlertDialog dialog = create();
1114             dialog.show();
1115             return dialog;
1116         }
1117     }
1118 
1119 }
1120