PopupWindow.java revision ab36acb39941ce981dddda9f9cf4d2d23a56fd26
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
17package android.widget;
18
19import com.android.internal.R;
20
21import android.content.Context;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.PixelFormat;
25import android.graphics.Rect;
26import android.graphics.drawable.Drawable;
27import android.graphics.drawable.StateListDrawable;
28import android.os.IBinder;
29import android.util.AttributeSet;
30import android.util.DisplayMetrics;
31import android.view.Gravity;
32import android.view.KeyEvent;
33import android.view.MotionEvent;
34import android.view.View;
35import android.view.View.OnTouchListener;
36import android.view.ViewGroup;
37import android.view.ViewTreeObserver;
38import android.view.ViewTreeObserver.OnScrollChangedListener;
39import android.view.WindowManager;
40
41import java.lang.ref.WeakReference;
42
43/**
44 * <p>A popup window that can be used to display an arbitrary view. The popup
45 * windows is a floating container that appears on top of the current
46 * activity.</p>
47 *
48 * @see android.widget.AutoCompleteTextView
49 * @see android.widget.Spinner
50 */
51public class PopupWindow {
52    /**
53     * Mode for {@link #setInputMethodMode(int)}: the requirements for the
54     * input method should be based on the focusability of the popup.  That is
55     * if it is focusable than it needs to work with the input method, else
56     * it doesn't.
57     */
58    public static final int INPUT_METHOD_FROM_FOCUSABLE = 0;
59
60    /**
61     * Mode for {@link #setInputMethodMode(int)}: this popup always needs to
62     * work with an input method, regardless of whether it is focusable.  This
63     * means that it will always be displayed so that the user can also operate
64     * the input method while it is shown.
65     */
66    public static final int INPUT_METHOD_NEEDED = 1;
67
68    /**
69     * Mode for {@link #setInputMethodMode(int)}: this popup never needs to
70     * work with an input method, regardless of whether it is focusable.  This
71     * means that it will always be displayed to use as much space on the
72     * screen as needed, regardless of whether this covers the input method.
73     */
74    public static final int INPUT_METHOD_NOT_NEEDED = 2;
75
76    private Context mContext;
77    private WindowManager mWindowManager;
78
79    private boolean mIsShowing;
80    private boolean mIsDropdown;
81
82    private View mContentView;
83    private View mPopupView;
84    private boolean mFocusable;
85    private int mInputMethodMode = INPUT_METHOD_FROM_FOCUSABLE;
86    private int mSoftInputMode;
87    private boolean mTouchable = true;
88    private boolean mOutsideTouchable = false;
89    private boolean mClippingEnabled = true;
90    private boolean mSplitTouchEnabled;
91    private boolean mLayoutInScreen;
92    private boolean mClipToScreen;
93
94    private OnTouchListener mTouchInterceptor;
95
96    private int mWidthMode;
97    private int mWidth;
98    private int mLastWidth;
99    private int mHeightMode;
100    private int mHeight;
101    private int mLastHeight;
102
103    private int mPopupWidth;
104    private int mPopupHeight;
105
106    private int[] mDrawingLocation = new int[2];
107    private int[] mScreenLocation = new int[2];
108    private Rect mTempRect = new Rect();
109
110    private Drawable mBackground;
111    private Drawable mAboveAnchorBackgroundDrawable;
112    private Drawable mBelowAnchorBackgroundDrawable;
113
114    private boolean mAboveAnchor;
115    private int mWindowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
116
117    private OnDismissListener mOnDismissListener;
118    private boolean mIgnoreCheekPress = false;
119
120    private int mAnimationStyle = -1;
121
122    private static final int[] ABOVE_ANCHOR_STATE_SET = new int[] {
123        com.android.internal.R.attr.state_above_anchor
124    };
125
126    private WeakReference<View> mAnchor;
127    private OnScrollChangedListener mOnScrollChangedListener =
128        new OnScrollChangedListener() {
129            public void onScrollChanged() {
130                View anchor = mAnchor != null ? mAnchor.get() : null;
131                if (anchor != null && mPopupView != null) {
132                    WindowManager.LayoutParams p = (WindowManager.LayoutParams)
133                            mPopupView.getLayoutParams();
134
135                    updateAboveAnchor(findDropDownPosition(anchor, p, mAnchorXoff, mAnchorYoff));
136                    update(p.x, p.y, -1, -1, true);
137                }
138            }
139        };
140    private int mAnchorXoff, mAnchorYoff;
141
142    /**
143     * <p>Create a new empty, non focusable popup window of dimension (0,0).</p>
144     *
145     * <p>The popup does provide a background.</p>
146     */
147    public PopupWindow(Context context) {
148        this(context, null);
149    }
150
151    /**
152     * <p>Create a new empty, non focusable popup window of dimension (0,0).</p>
153     *
154     * <p>The popup does provide a background.</p>
155     */
156    public PopupWindow(Context context, AttributeSet attrs) {
157        this(context, attrs, com.android.internal.R.attr.popupWindowStyle);
158    }
159
160    /**
161     * <p>Create a new empty, non focusable popup window of dimension (0,0).</p>
162     *
163     * <p>The popup does provide a background.</p>
164     */
165    public PopupWindow(Context context, AttributeSet attrs, int defStyle) {
166        this(context, attrs, defStyle, 0);
167    }
168
169    /**
170     * <p>Create a new, empty, non focusable popup window of dimension (0,0).</p>
171     *
172     * <p>The popup does not provide a background.</p>
173     */
174    public PopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
175        mContext = context;
176        mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
177
178        TypedArray a =
179            context.obtainStyledAttributes(
180                attrs, com.android.internal.R.styleable.PopupWindow, defStyleAttr, defStyleRes);
181
182        mBackground = a.getDrawable(R.styleable.PopupWindow_popupBackground);
183
184        final int animStyle = a.getResourceId(R.styleable.PopupWindow_popupAnimationStyle, -1);
185        mAnimationStyle = animStyle == com.android.internal.R.style.Animation_PopupWindow ? -1 :
186                animStyle;
187
188        // If this is a StateListDrawable, try to find and store the drawable to be
189        // used when the drop-down is placed above its anchor view, and the one to be
190        // used when the drop-down is placed below its anchor view. We extract
191        // the drawables ourselves to work around a problem with using refreshDrawableState
192        // that it will take into account the padding of all drawables specified in a
193        // StateListDrawable, thus adding superfluous padding to drop-down views.
194        //
195        // We assume a StateListDrawable will have a drawable for ABOVE_ANCHOR_STATE_SET and
196        // at least one other drawable, intended for the 'below-anchor state'.
197        if (mBackground instanceof StateListDrawable) {
198            StateListDrawable background = (StateListDrawable) mBackground;
199
200            // Find the above-anchor view - this one's easy, it should be labeled as such.
201            int aboveAnchorStateIndex = background.getStateDrawableIndex(ABOVE_ANCHOR_STATE_SET);
202
203            // Now, for the below-anchor view, look for any other drawable specified in the
204            // StateListDrawable which is not for the above-anchor state and use that.
205            int count = background.getStateCount();
206            int belowAnchorStateIndex = -1;
207            for (int i = 0; i < count; i++) {
208                if (i != aboveAnchorStateIndex) {
209                    belowAnchorStateIndex = i;
210                    break;
211                }
212            }
213
214            // Store the drawables we found, if we found them. Otherwise, set them both
215            // to null so that we'll just use refreshDrawableState.
216            if (aboveAnchorStateIndex != -1 && belowAnchorStateIndex != -1) {
217                mAboveAnchorBackgroundDrawable = background.getStateDrawable(aboveAnchorStateIndex);
218                mBelowAnchorBackgroundDrawable = background.getStateDrawable(belowAnchorStateIndex);
219            } else {
220                mBelowAnchorBackgroundDrawable = null;
221                mAboveAnchorBackgroundDrawable = null;
222            }
223        }
224
225        a.recycle();
226    }
227
228    /**
229     * <p>Create a new empty, non focusable popup window of dimension (0,0).</p>
230     *
231     * <p>The popup does not provide any background. This should be handled
232     * by the content view.</p>
233     */
234    public PopupWindow() {
235        this(null, 0, 0);
236    }
237
238    /**
239     * <p>Create a new non focusable popup window which can display the
240     * <tt>contentView</tt>. The dimension of the window are (0,0).</p>
241     *
242     * <p>The popup does not provide any background. This should be handled
243     * by the content view.</p>
244     *
245     * @param contentView the popup's content
246     */
247    public PopupWindow(View contentView) {
248        this(contentView, 0, 0);
249    }
250
251    /**
252     * <p>Create a new empty, non focusable popup window. The dimension of the
253     * window must be passed to this constructor.</p>
254     *
255     * <p>The popup does not provide any background. This should be handled
256     * by the content view.</p>
257     *
258     * @param width the popup's width
259     * @param height the popup's height
260     */
261    public PopupWindow(int width, int height) {
262        this(null, width, height);
263    }
264
265    /**
266     * <p>Create a new non focusable popup window which can display the
267     * <tt>contentView</tt>. The dimension of the window must be passed to
268     * this constructor.</p>
269     *
270     * <p>The popup does not provide any background. This should be handled
271     * by the content view.</p>
272     *
273     * @param contentView the popup's content
274     * @param width the popup's width
275     * @param height the popup's height
276     */
277    public PopupWindow(View contentView, int width, int height) {
278        this(contentView, width, height, false);
279    }
280
281    /**
282     * <p>Create a new popup window which can display the <tt>contentView</tt>.
283     * The dimension of the window must be passed to this constructor.</p>
284     *
285     * <p>The popup does not provide any background. This should be handled
286     * by the content view.</p>
287     *
288     * @param contentView the popup's content
289     * @param width the popup's width
290     * @param height the popup's height
291     * @param focusable true if the popup can be focused, false otherwise
292     */
293    public PopupWindow(View contentView, int width, int height, boolean focusable) {
294        if (contentView != null) {
295            mContext = contentView.getContext();
296            mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
297        }
298        setContentView(contentView);
299        setWidth(width);
300        setHeight(height);
301        setFocusable(focusable);
302    }
303
304    /**
305     * <p>Return the drawable used as the popup window's background.</p>
306     *
307     * @return the background drawable or null
308     */
309    public Drawable getBackground() {
310        return mBackground;
311    }
312
313    /**
314     * <p>Change the background drawable for this popup window. The background
315     * can be set to null.</p>
316     *
317     * @param background the popup's background
318     */
319    public void setBackgroundDrawable(Drawable background) {
320        mBackground = background;
321    }
322
323    /**
324     * <p>Return the animation style to use the popup appears and disappears</p>
325     *
326     * @return the animation style to use the popup appears and disappears
327     */
328    public int getAnimationStyle() {
329        return mAnimationStyle;
330    }
331
332    /**
333     * Set the flag on popup to ignore cheek press eventt; by default this flag
334     * is set to false
335     * which means the pop wont ignore cheek press dispatch events.
336     *
337     * <p>If the popup is showing, calling this method will take effect only
338     * the next time the popup is shown or through a manual call to one of
339     * the {@link #update()} methods.</p>
340     *
341     * @see #update()
342     */
343    public void setIgnoreCheekPress() {
344        mIgnoreCheekPress = true;
345    }
346
347
348    /**
349     * <p>Change the animation style resource for this popup.</p>
350     *
351     * <p>If the popup is showing, calling this method will take effect only
352     * the next time the popup is shown or through a manual call to one of
353     * the {@link #update()} methods.</p>
354     *
355     * @param animationStyle animation style to use when the popup appears
356     *      and disappears.  Set to -1 for the default animation, 0 for no
357     *      animation, or a resource identifier for an explicit animation.
358     *
359     * @see #update()
360     */
361    public void setAnimationStyle(int animationStyle) {
362        mAnimationStyle = animationStyle;
363    }
364
365    /**
366     * <p>Return the view used as the content of the popup window.</p>
367     *
368     * @return a {@link android.view.View} representing the popup's content
369     *
370     * @see #setContentView(android.view.View)
371     */
372    public View getContentView() {
373        return mContentView;
374    }
375
376    /**
377     * <p>Change the popup's content. The content is represented by an instance
378     * of {@link android.view.View}.</p>
379     *
380     * <p>This method has no effect if called when the popup is showing.  To
381     * apply it while a popup is showing, call </p>
382     *
383     * @param contentView the new content for the popup
384     *
385     * @see #getContentView()
386     * @see #isShowing()
387     */
388    public void setContentView(View contentView) {
389        if (isShowing()) {
390            return;
391        }
392
393        mContentView = contentView;
394
395        if (mContext == null) {
396            mContext = mContentView.getContext();
397        }
398
399        if (mWindowManager == null) {
400            mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
401        }
402    }
403
404    /**
405     * Set a callback for all touch events being dispatched to the popup
406     * window.
407     */
408    public void setTouchInterceptor(OnTouchListener l) {
409        mTouchInterceptor = l;
410    }
411
412    /**
413     * <p>Indicate whether the popup window can grab the focus.</p>
414     *
415     * @return true if the popup is focusable, false otherwise
416     *
417     * @see #setFocusable(boolean)
418     */
419    public boolean isFocusable() {
420        return mFocusable;
421    }
422
423    /**
424     * <p>Changes the focusability of the popup window. When focusable, the
425     * window will grab the focus from the current focused widget if the popup
426     * contains a focusable {@link android.view.View}.  By default a popup
427     * window is not focusable.</p>
428     *
429     * <p>If the popup is showing, calling this method will take effect only
430     * the next time the popup is shown or through a manual call to one of
431     * the {@link #update()} methods.</p>
432     *
433     * @param focusable true if the popup should grab focus, false otherwise.
434     *
435     * @see #isFocusable()
436     * @see #isShowing()
437     * @see #update()
438     */
439    public void setFocusable(boolean focusable) {
440        mFocusable = focusable;
441    }
442
443    /**
444     * Return the current value in {@link #setInputMethodMode(int)}.
445     *
446     * @see #setInputMethodMode(int)
447     */
448    public int getInputMethodMode() {
449        return mInputMethodMode;
450
451    }
452
453    /**
454     * Control how the popup operates with an input method: one of
455     * {@link #INPUT_METHOD_FROM_FOCUSABLE}, {@link #INPUT_METHOD_NEEDED},
456     * or {@link #INPUT_METHOD_NOT_NEEDED}.
457     *
458     * <p>If the popup is showing, calling this method will take effect only
459     * the next time the popup is shown or through a manual call to one of
460     * the {@link #update()} methods.</p>
461     *
462     * @see #getInputMethodMode()
463     * @see #update()
464     */
465    public void setInputMethodMode(int mode) {
466        mInputMethodMode = mode;
467    }
468
469    /**
470     * Sets the operating mode for the soft input area.
471     *
472     * @param mode The desired mode, see
473     *        {@link android.view.WindowManager.LayoutParams#softInputMode}
474     *        for the full list
475     *
476     * @see android.view.WindowManager.LayoutParams#softInputMode
477     * @see #getSoftInputMode()
478     */
479    public void setSoftInputMode(int mode) {
480        mSoftInputMode = mode;
481    }
482
483    /**
484     * Returns the current value in {@link #setSoftInputMode(int)}.
485     *
486     * @see #setSoftInputMode(int)
487     * @see android.view.WindowManager.LayoutParams#softInputMode
488     */
489    public int getSoftInputMode() {
490        return mSoftInputMode;
491    }
492
493    /**
494     * <p>Indicates whether the popup window receives touch events.</p>
495     *
496     * @return true if the popup is touchable, false otherwise
497     *
498     * @see #setTouchable(boolean)
499     */
500    public boolean isTouchable() {
501        return mTouchable;
502    }
503
504    /**
505     * <p>Changes the touchability of the popup window. When touchable, the
506     * window will receive touch events, otherwise touch events will go to the
507     * window below it. By default the window is touchable.</p>
508     *
509     * <p>If the popup is showing, calling this method will take effect only
510     * the next time the popup is shown or through a manual call to one of
511     * the {@link #update()} methods.</p>
512     *
513     * @param touchable true if the popup should receive touch events, false otherwise
514     *
515     * @see #isTouchable()
516     * @see #isShowing()
517     * @see #update()
518     */
519    public void setTouchable(boolean touchable) {
520        mTouchable = touchable;
521    }
522
523    /**
524     * <p>Indicates whether the popup window will be informed of touch events
525     * outside of its window.</p>
526     *
527     * @return true if the popup is outside touchable, false otherwise
528     *
529     * @see #setOutsideTouchable(boolean)
530     */
531    public boolean isOutsideTouchable() {
532        return mOutsideTouchable;
533    }
534
535    /**
536     * <p>Controls whether the pop-up will be informed of touch events outside
537     * of its window.  This only makes sense for pop-ups that are touchable
538     * but not focusable, which means touches outside of the window will
539     * be delivered to the window behind.  The default is false.</p>
540     *
541     * <p>If the popup is showing, calling this method will take effect only
542     * the next time the popup is shown or through a manual call to one of
543     * the {@link #update()} methods.</p>
544     *
545     * @param touchable true if the popup should receive outside
546     * touch events, false otherwise
547     *
548     * @see #isOutsideTouchable()
549     * @see #isShowing()
550     * @see #update()
551     */
552    public void setOutsideTouchable(boolean touchable) {
553        mOutsideTouchable = touchable;
554    }
555
556    /**
557     * <p>Indicates whether clipping of the popup window is enabled.</p>
558     *
559     * @return true if the clipping is enabled, false otherwise
560     *
561     * @see #setClippingEnabled(boolean)
562     */
563    public boolean isClippingEnabled() {
564        return mClippingEnabled;
565    }
566
567    /**
568     * <p>Allows the popup window to extend beyond the bounds of the screen. By default the
569     * window is clipped to the screen boundaries. Setting this to false will allow windows to be
570     * accurately positioned.</p>
571     *
572     * <p>If the popup is showing, calling this method will take effect only
573     * the next time the popup is shown or through a manual call to one of
574     * the {@link #update()} methods.</p>
575     *
576     * @param enabled false if the window should be allowed to extend outside of the screen
577     * @see #isShowing()
578     * @see #isClippingEnabled()
579     * @see #update()
580     */
581    public void setClippingEnabled(boolean enabled) {
582        mClippingEnabled = enabled;
583    }
584
585    /**
586     * Clip this popup window to the screen, but not to the containing window.
587     *
588     * @param enabled True to clip to the screen.
589     * @hide
590     */
591    public void setClipToScreenEnabled(boolean enabled) {
592        mClipToScreen = enabled;
593        setClippingEnabled(!enabled);
594    }
595
596    /**
597     * <p>Indicates whether the popup window supports splitting touches.</p>
598     *
599     * @return true if the touch splitting is enabled, false otherwise
600     *
601     * @see #setSplitTouchEnabled(boolean)
602     * @hide
603     */
604    public boolean isSplitTouchEnabled() {
605        return mSplitTouchEnabled;
606    }
607
608    /**
609     * <p>Allows the popup window to split touches across other windows that also
610     * support split touch.  When this flag is not set, the first pointer
611     * that goes down determines the window to which all subsequent touches
612     * go until all pointers go up.  When this flag is set, each pointer
613     * (not necessarily the first) that goes down determines the window
614     * to which all subsequent touches of that pointer will go until that
615     * pointer goes up thereby enabling touches with multiple pointers
616     * to be split across multiple windows.</p>
617     *
618     * @param enabled true if the split touches should be enabled, false otherwise
619     * @see #isSplitTouchEnabled()
620     * @hide
621     */
622    public void setSplitTouchEnabled(boolean enabled) {
623        mSplitTouchEnabled = enabled;
624    }
625
626    /**
627     * <p>Indicates whether the popup window will be forced into using absolute screen coordinates
628     * for positioning.</p>
629     *
630     * @return true if the window will always be positioned in screen coordinates.
631     * @hide
632     */
633    public boolean isLayoutInScreenEnabled() {
634        return mLayoutInScreen;
635    }
636
637    /**
638     * <p>Allows the popup window to force the flag
639     * {@link WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN}, overriding default behavior.
640     * This will cause the popup to be positioned in absolute screen coordinates.</p>
641     *
642     * @param enabled true if the popup should always be positioned in screen coordinates
643     * @hide
644     */
645    public void setLayoutInScreenEnabled(boolean enabled) {
646        mLayoutInScreen = enabled;
647    }
648
649    /**
650     * Set the layout type for this window. Should be one of the TYPE constants defined in
651     * {@link WindowManager.LayoutParams}.
652     *
653     * @param layoutType Layout type for this window.
654     * @hide
655     */
656    public void setWindowLayoutType(int layoutType) {
657        mWindowLayoutType = layoutType;
658    }
659
660    /**
661     * @return The layout type for this window.
662     * @hide
663     */
664    public int getWindowLayoutType() {
665        return mWindowLayoutType;
666    }
667
668    /**
669     * <p>Change the width and height measure specs that are given to the
670     * window manager by the popup.  By default these are 0, meaning that
671     * the current width or height is requested as an explicit size from
672     * the window manager.  You can supply
673     * {@link ViewGroup.LayoutParams#WRAP_CONTENT} or
674     * {@link ViewGroup.LayoutParams#MATCH_PARENT} to have that measure
675     * spec supplied instead, replacing the absolute width and height that
676     * has been set in the popup.</p>
677     *
678     * <p>If the popup is showing, calling this method will take effect only
679     * the next time the popup is shown.</p>
680     *
681     * @param widthSpec an explicit width measure spec mode, either
682     * {@link ViewGroup.LayoutParams#WRAP_CONTENT},
683     * {@link ViewGroup.LayoutParams#MATCH_PARENT}, or 0 to use the absolute
684     * width.
685     * @param heightSpec an explicit height measure spec mode, either
686     * {@link ViewGroup.LayoutParams#WRAP_CONTENT},
687     * {@link ViewGroup.LayoutParams#MATCH_PARENT}, or 0 to use the absolute
688     * height.
689     */
690    public void setWindowLayoutMode(int widthSpec, int heightSpec) {
691        mWidthMode = widthSpec;
692        mHeightMode = heightSpec;
693    }
694
695    /**
696     * <p>Return this popup's height MeasureSpec</p>
697     *
698     * @return the height MeasureSpec of the popup
699     *
700     * @see #setHeight(int)
701     */
702    public int getHeight() {
703        return mHeight;
704    }
705
706    /**
707     * <p>Change the popup's height MeasureSpec</p>
708     *
709     * <p>If the popup is showing, calling this method will take effect only
710     * the next time the popup is shown.</p>
711     *
712     * @param height the height MeasureSpec of the popup
713     *
714     * @see #getHeight()
715     * @see #isShowing()
716     */
717    public void setHeight(int height) {
718        mHeight = height;
719    }
720
721    /**
722     * <p>Return this popup's width MeasureSpec</p>
723     *
724     * @return the width MeasureSpec of the popup
725     *
726     * @see #setWidth(int)
727     */
728    public int getWidth() {
729        return mWidth;
730    }
731
732    /**
733     * <p>Change the popup's width MeasureSpec</p>
734     *
735     * <p>If the popup is showing, calling this method will take effect only
736     * the next time the popup is shown.</p>
737     *
738     * @param width the width MeasureSpec of the popup
739     *
740     * @see #getWidth()
741     * @see #isShowing()
742     */
743    public void setWidth(int width) {
744        mWidth = width;
745    }
746
747    /**
748     * <p>Indicate whether this popup window is showing on screen.</p>
749     *
750     * @return true if the popup is showing, false otherwise
751     */
752    public boolean isShowing() {
753        return mIsShowing;
754    }
755
756    /**
757     * <p>
758     * Display the content view in a popup window at the specified location. If the popup window
759     * cannot fit on screen, it will be clipped. See {@link android.view.WindowManager.LayoutParams}
760     * for more information on how gravity and the x and y parameters are related. Specifying
761     * a gravity of {@link android.view.Gravity#NO_GRAVITY} is similar to specifying
762     * <code>Gravity.LEFT | Gravity.TOP</code>.
763     * </p>
764     *
765     * @param parent a parent view to get the {@link android.view.View#getWindowToken()} token from
766     * @param gravity the gravity which controls the placement of the popup window
767     * @param x the popup's x location offset
768     * @param y the popup's y location offset
769     */
770    public void showAtLocation(View parent, int gravity, int x, int y) {
771        if (isShowing() || mContentView == null) {
772            return;
773        }
774
775        unregisterForScrollChanged();
776
777        mIsShowing = true;
778        mIsDropdown = false;
779
780        WindowManager.LayoutParams p = createPopupLayout(parent.getWindowToken());
781        p.windowAnimations = computeAnimationResource();
782
783        preparePopup(p);
784        if (gravity == Gravity.NO_GRAVITY) {
785            gravity = Gravity.TOP | Gravity.LEFT;
786        }
787        p.gravity = gravity;
788        p.x = x;
789        p.y = y;
790        if (mHeightMode < 0) p.height = mLastHeight = mHeightMode;
791        if (mWidthMode < 0) p.width = mLastWidth = mWidthMode;
792        invokePopup(p);
793    }
794
795    /**
796     * <p>Display the content view in a popup window anchored to the bottom-left
797     * corner of the anchor view. If there is not enough room on screen to show
798     * the popup in its entirety, this method tries to find a parent scroll
799     * view to scroll. If no parent scroll view can be scrolled, the bottom-left
800     * corner of the popup is pinned at the top left corner of the anchor view.</p>
801     *
802     * @param anchor the view on which to pin the popup window
803     *
804     * @see #dismiss()
805     */
806    public void showAsDropDown(View anchor) {
807        showAsDropDown(anchor, 0, 0);
808    }
809
810    /**
811     * <p>Display the content view in a popup window anchored to the bottom-left
812     * corner of the anchor view offset by the specified x and y coordinates.
813     * If there is not enough room on screen to show
814     * the popup in its entirety, this method tries to find a parent scroll
815     * view to scroll. If no parent scroll view can be scrolled, the bottom-left
816     * corner of the popup is pinned at the top left corner of the anchor view.</p>
817     * <p>If the view later scrolls to move <code>anchor</code> to a different
818     * location, the popup will be moved correspondingly.</p>
819     *
820     * @param anchor the view on which to pin the popup window
821     *
822     * @see #dismiss()
823     */
824    public void showAsDropDown(View anchor, int xoff, int yoff) {
825        if (isShowing() || mContentView == null) {
826            return;
827        }
828
829        registerForScrollChanged(anchor, xoff, yoff);
830
831        mIsShowing = true;
832        mIsDropdown = true;
833
834        WindowManager.LayoutParams p = createPopupLayout(anchor.getWindowToken());
835        preparePopup(p);
836
837        updateAboveAnchor(findDropDownPosition(anchor, p, xoff, yoff));
838
839        if (mHeightMode < 0) p.height = mLastHeight = mHeightMode;
840        if (mWidthMode < 0) p.width = mLastWidth = mWidthMode;
841
842        p.windowAnimations = computeAnimationResource();
843
844        invokePopup(p);
845    }
846
847    private void updateAboveAnchor(boolean aboveAnchor) {
848        if (aboveAnchor != mAboveAnchor) {
849            mAboveAnchor = aboveAnchor;
850
851            if (mBackground != null) {
852                // If the background drawable provided was a StateListDrawable with above-anchor
853                // and below-anchor states, use those. Otherwise rely on refreshDrawableState to
854                // do the job.
855                if (mAboveAnchorBackgroundDrawable != null) {
856                    if (mAboveAnchor) {
857                        mPopupView.setBackgroundDrawable(mAboveAnchorBackgroundDrawable);
858                    } else {
859                        mPopupView.setBackgroundDrawable(mBelowAnchorBackgroundDrawable);
860                    }
861                } else {
862                    mPopupView.refreshDrawableState();
863                }
864            }
865        }
866    }
867
868    /**
869     * Indicates whether the popup is showing above (the y coordinate of the popup's bottom
870     * is less than the y coordinate of the anchor) or below the anchor view (the y coordinate
871     * of the popup is greater than y coordinate of the anchor's bottom).
872     *
873     * The value returned
874     * by this method is meaningful only after {@link #showAsDropDown(android.view.View)}
875     * or {@link #showAsDropDown(android.view.View, int, int)} was invoked.
876     *
877     * @return True if this popup is showing above the anchor view, false otherwise.
878     */
879    public boolean isAboveAnchor() {
880        return mAboveAnchor;
881    }
882
883    /**
884     * <p>Prepare the popup by embedding in into a new ViewGroup if the
885     * background drawable is not null. If embedding is required, the layout
886     * parameters' height is mnodified to take into account the background's
887     * padding.</p>
888     *
889     * @param p the layout parameters of the popup's content view
890     */
891    private void preparePopup(WindowManager.LayoutParams p) {
892        if (mContentView == null || mContext == null || mWindowManager == null) {
893            throw new IllegalStateException("You must specify a valid content view by "
894                    + "calling setContentView() before attempting to show the popup.");
895        }
896
897        if (mBackground != null) {
898            final ViewGroup.LayoutParams layoutParams = mContentView.getLayoutParams();
899            int height = ViewGroup.LayoutParams.MATCH_PARENT;
900            if (layoutParams != null &&
901                    layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
902                height = ViewGroup.LayoutParams.WRAP_CONTENT;
903            }
904
905            // when a background is available, we embed the content view
906            // within another view that owns the background drawable
907            PopupViewContainer popupViewContainer = new PopupViewContainer(mContext);
908            PopupViewContainer.LayoutParams listParams = new PopupViewContainer.LayoutParams(
909                    ViewGroup.LayoutParams.MATCH_PARENT, height
910            );
911            popupViewContainer.setBackgroundDrawable(mBackground);
912            popupViewContainer.addView(mContentView, listParams);
913
914            mPopupView = popupViewContainer;
915        } else {
916            mPopupView = mContentView;
917        }
918        mPopupWidth = p.width;
919        mPopupHeight = p.height;
920    }
921
922    /**
923     * <p>Invoke the popup window by adding the content view to the window
924     * manager.</p>
925     *
926     * <p>The content view must be non-null when this method is invoked.</p>
927     *
928     * @param p the layout parameters of the popup's content view
929     */
930    private void invokePopup(WindowManager.LayoutParams p) {
931        p.packageName = mContext.getPackageName();
932        mWindowManager.addView(mPopupView, p);
933    }
934
935    /**
936     * <p>Generate the layout parameters for the popup window.</p>
937     *
938     * @param token the window token used to bind the popup's window
939     *
940     * @return the layout parameters to pass to the window manager
941     */
942    private WindowManager.LayoutParams createPopupLayout(IBinder token) {
943        // generates the layout parameters for the drop down
944        // we want a fixed size view located at the bottom left of the anchor
945        WindowManager.LayoutParams p = new WindowManager.LayoutParams();
946        // these gravity settings put the view at the top left corner of the
947        // screen. The view is then positioned to the appropriate location
948        // by setting the x and y offsets to match the anchor's bottom
949        // left corner
950        p.gravity = Gravity.LEFT | Gravity.TOP;
951        p.width = mLastWidth = mWidth;
952        p.height = mLastHeight = mHeight;
953        if (mBackground != null) {
954            p.format = mBackground.getOpacity();
955        } else {
956            p.format = PixelFormat.TRANSLUCENT;
957        }
958        p.flags = computeFlags(p.flags);
959        p.type = mWindowLayoutType;
960        p.token = token;
961        p.softInputMode = mSoftInputMode;
962        p.setTitle("PopupWindow:" + Integer.toHexString(hashCode()));
963
964        return p;
965    }
966
967    private int computeFlags(int curFlags) {
968        curFlags &= ~(
969                WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES |
970                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
971                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
972                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
973                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
974                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM |
975                WindowManager.LayoutParams.FLAG_SPLIT_TOUCH);
976        if(mIgnoreCheekPress) {
977            curFlags |= WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES;
978        }
979        if (!mFocusable) {
980            curFlags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
981            if (mInputMethodMode == INPUT_METHOD_NEEDED) {
982                curFlags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
983            }
984        } else if (mInputMethodMode == INPUT_METHOD_NOT_NEEDED) {
985            curFlags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
986        }
987        if (!mTouchable) {
988            curFlags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
989        }
990        if (mOutsideTouchable) {
991            curFlags |= WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
992        }
993        if (!mClippingEnabled) {
994            curFlags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
995        }
996        if (mSplitTouchEnabled) {
997            curFlags |= WindowManager.LayoutParams.FLAG_SPLIT_TOUCH;
998        }
999        if (mLayoutInScreen) {
1000            curFlags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
1001        }
1002        return curFlags;
1003    }
1004
1005    private int computeAnimationResource() {
1006        if (mAnimationStyle == -1) {
1007            if (mIsDropdown) {
1008                return mAboveAnchor
1009                        ? com.android.internal.R.style.Animation_DropDownUp
1010                        : com.android.internal.R.style.Animation_DropDownDown;
1011            }
1012            return 0;
1013        }
1014        return mAnimationStyle;
1015    }
1016
1017    /**
1018     * <p>Positions the popup window on screen. When the popup window is too
1019     * tall to fit under the anchor, a parent scroll view is seeked and scrolled
1020     * up to reclaim space. If scrolling is not possible or not enough, the
1021     * popup window gets moved on top of the anchor.</p>
1022     *
1023     * <p>The height must have been set on the layout parameters prior to
1024     * calling this method.</p>
1025     *
1026     * @param anchor the view on which the popup window must be anchored
1027     * @param p the layout parameters used to display the drop down
1028     *
1029     * @return true if the popup is translated upwards to fit on screen
1030     */
1031    private boolean findDropDownPosition(View anchor, WindowManager.LayoutParams p,
1032            int xoff, int yoff) {
1033
1034        anchor.getLocationInWindow(mDrawingLocation);
1035        p.x = mDrawingLocation[0] + xoff;
1036        p.y = mDrawingLocation[1] + anchor.getHeight() + yoff;
1037
1038        boolean onTop = false;
1039
1040        p.gravity = Gravity.LEFT | Gravity.TOP;
1041
1042        anchor.getLocationOnScreen(mScreenLocation);
1043        final Rect displayFrame = new Rect();
1044        anchor.getWindowVisibleDisplayFrame(displayFrame);
1045
1046        final View root = anchor.getRootView();
1047        if (p.y + mPopupHeight > displayFrame.bottom || p.x + mPopupWidth - root.getWidth() > 0) {
1048            // if the drop down disappears at the bottom of the screen. we try to
1049            // scroll a parent scrollview or move the drop down back up on top of
1050            // the edit box
1051            int scrollX = anchor.getScrollX();
1052            int scrollY = anchor.getScrollY();
1053            Rect r = new Rect(scrollX, scrollY,  scrollX + mPopupWidth + xoff,
1054                    scrollY + mPopupHeight + anchor.getHeight() + yoff);
1055            anchor.requestRectangleOnScreen(r, true);
1056
1057            // now we re-evaluate the space available, and decide from that
1058            // whether the pop-up will go above or below the anchor.
1059            anchor.getLocationInWindow(mDrawingLocation);
1060            p.x = mDrawingLocation[0] + xoff;
1061            p.y = mDrawingLocation[1] + anchor.getHeight() + yoff;
1062
1063            // determine whether there is more space above or below the anchor
1064            anchor.getLocationOnScreen(mScreenLocation);
1065
1066            onTop = (displayFrame.bottom - mScreenLocation[1] - anchor.getHeight() - yoff) <
1067                    (mScreenLocation[1] - yoff - displayFrame.top);
1068            if (onTop) {
1069                p.gravity = Gravity.LEFT | Gravity.BOTTOM;
1070                p.y = root.getHeight() - mDrawingLocation[1] + yoff;
1071            } else {
1072                p.y = mDrawingLocation[1] + anchor.getHeight() + yoff;
1073            }
1074        }
1075
1076        if (mClipToScreen) {
1077            final int displayFrameWidth = displayFrame.right - displayFrame.left;
1078
1079            int right = p.x + p.width;
1080            if (right > displayFrameWidth) {
1081                p.x -= right - displayFrameWidth;
1082            }
1083            if (p.x < displayFrame.left) {
1084                p.x = displayFrame.left;
1085                p.width = Math.min(p.width, displayFrameWidth);
1086            }
1087
1088            p.y = Math.max(p.y, displayFrame.top);
1089        }
1090
1091        p.gravity |= Gravity.DISPLAY_CLIP_VERTICAL;
1092
1093        return onTop;
1094    }
1095
1096    /**
1097     * Returns the maximum height that is available for the popup to be
1098     * completely shown. It is recommended that this height be the maximum for
1099     * the popup's height, otherwise it is possible that the popup will be
1100     * clipped.
1101     *
1102     * @param anchor The view on which the popup window must be anchored.
1103     * @return The maximum available height for the popup to be completely
1104     *         shown.
1105     */
1106    public int getMaxAvailableHeight(View anchor) {
1107        return getMaxAvailableHeight(anchor, 0);
1108    }
1109
1110    /**
1111     * Returns the maximum height that is available for the popup to be
1112     * completely shown. It is recommended that this height be the maximum for
1113     * the popup's height, otherwise it is possible that the popup will be
1114     * clipped.
1115     *
1116     * @param anchor The view on which the popup window must be anchored.
1117     * @param yOffset y offset from the view's bottom edge
1118     * @return The maximum available height for the popup to be completely
1119     *         shown.
1120     */
1121    public int getMaxAvailableHeight(View anchor, int yOffset) {
1122        return getMaxAvailableHeight(anchor, yOffset, false);
1123    }
1124
1125    /**
1126     * Returns the maximum height that is available for the popup to be
1127     * completely shown, optionally ignoring any bottom decorations such as
1128     * the input method. It is recommended that this height be the maximum for
1129     * the popup's height, otherwise it is possible that the popup will be
1130     * clipped.
1131     *
1132     * @param anchor The view on which the popup window must be anchored.
1133     * @param yOffset y offset from the view's bottom edge
1134     * @param ignoreBottomDecorations if true, the height returned will be
1135     *        all the way to the bottom of the display, ignoring any
1136     *        bottom decorations
1137     * @return The maximum available height for the popup to be completely
1138     *         shown.
1139     *
1140     * @hide Pending API council approval.
1141     */
1142    public int getMaxAvailableHeight(View anchor, int yOffset, boolean ignoreBottomDecorations) {
1143        final Rect displayFrame = new Rect();
1144        anchor.getWindowVisibleDisplayFrame(displayFrame);
1145
1146        final int[] anchorPos = mDrawingLocation;
1147        anchor.getLocationOnScreen(anchorPos);
1148
1149        int bottomEdge = displayFrame.bottom;
1150        if (ignoreBottomDecorations) {
1151            Resources res = anchor.getContext().getResources();
1152            bottomEdge = res.getDisplayMetrics().heightPixels -
1153                    (int) res.getDimension(com.android.internal.R.dimen.screen_margin_bottom);
1154        }
1155        final int distanceToBottom = bottomEdge - (anchorPos[1] + anchor.getHeight()) - yOffset;
1156        final int distanceToTop = anchorPos[1] - displayFrame.top + yOffset;
1157
1158        // anchorPos[1] is distance from anchor to top of screen
1159        int returnedHeight = Math.max(distanceToBottom, distanceToTop);
1160        if (mBackground != null) {
1161            mBackground.getPadding(mTempRect);
1162            returnedHeight -= mTempRect.top + mTempRect.bottom;
1163        }
1164
1165        return returnedHeight;
1166    }
1167
1168    /**
1169     * <p>Dispose of the popup window. This method can be invoked only after
1170     * {@link #showAsDropDown(android.view.View)} has been executed. Failing that, calling
1171     * this method will have no effect.</p>
1172     *
1173     * @see #showAsDropDown(android.view.View)
1174     */
1175    public void dismiss() {
1176        if (isShowing() && mPopupView != null) {
1177            unregisterForScrollChanged();
1178
1179            try {
1180                mWindowManager.removeView(mPopupView);
1181            } finally {
1182                if (mPopupView != mContentView && mPopupView instanceof ViewGroup) {
1183                    ((ViewGroup) mPopupView).removeView(mContentView);
1184                }
1185                mPopupView = null;
1186                mIsShowing = false;
1187
1188                if (mOnDismissListener != null) {
1189                    mOnDismissListener.onDismiss();
1190                }
1191            }
1192        }
1193    }
1194
1195    /**
1196     * Sets the listener to be called when the window is dismissed.
1197     *
1198     * @param onDismissListener The listener.
1199     */
1200    public void setOnDismissListener(OnDismissListener onDismissListener) {
1201        mOnDismissListener = onDismissListener;
1202    }
1203
1204    /**
1205     * Updates the state of the popup window, if it is currently being displayed,
1206     * from the currently set state.  This include:
1207     * {@link #setClippingEnabled(boolean)}, {@link #setFocusable(boolean)},
1208     * {@link #setIgnoreCheekPress()}, {@link #setInputMethodMode(int)},
1209     * {@link #setTouchable(boolean)}, and {@link #setAnimationStyle(int)}.
1210     */
1211    public void update() {
1212        if (!isShowing() || mContentView == null) {
1213            return;
1214        }
1215
1216        WindowManager.LayoutParams p = (WindowManager.LayoutParams)
1217                mPopupView.getLayoutParams();
1218
1219        boolean update = false;
1220
1221        final int newAnim = computeAnimationResource();
1222        if (newAnim != p.windowAnimations) {
1223            p.windowAnimations = newAnim;
1224            update = true;
1225        }
1226
1227        final int newFlags = computeFlags(p.flags);
1228        if (newFlags != p.flags) {
1229            p.flags = newFlags;
1230            update = true;
1231        }
1232
1233        if (update) {
1234            mWindowManager.updateViewLayout(mPopupView, p);
1235        }
1236    }
1237
1238    /**
1239     * <p>Updates the dimension of the popup window. Calling this function
1240     * also updates the window with the current popup state as described
1241     * for {@link #update()}.</p>
1242     *
1243     * @param width the new width
1244     * @param height the new height
1245     */
1246    public void update(int width, int height) {
1247        WindowManager.LayoutParams p = (WindowManager.LayoutParams)
1248                mPopupView.getLayoutParams();
1249        update(p.x, p.y, width, height, false);
1250    }
1251
1252    /**
1253     * <p>Updates the position and the dimension of the popup window. Width and
1254     * height can be set to -1 to update location only.  Calling this function
1255     * also updates the window with the current popup state as
1256     * described for {@link #update()}.</p>
1257     *
1258     * @param x the new x location
1259     * @param y the new y location
1260     * @param width the new width, can be -1 to ignore
1261     * @param height the new height, can be -1 to ignore
1262     */
1263    public void update(int x, int y, int width, int height) {
1264        update(x, y, width, height, false);
1265    }
1266
1267    /**
1268     * <p>Updates the position and the dimension of the popup window. Width and
1269     * height can be set to -1 to update location only.  Calling this function
1270     * also updates the window with the current popup state as
1271     * described for {@link #update()}.</p>
1272     *
1273     * @param x the new x location
1274     * @param y the new y location
1275     * @param width the new width, can be -1 to ignore
1276     * @param height the new height, can be -1 to ignore
1277     * @param force reposition the window even if the specified position
1278     *              already seems to correspond to the LayoutParams
1279     */
1280    public void update(int x, int y, int width, int height, boolean force) {
1281        if (width != -1) {
1282            mLastWidth = width;
1283            setWidth(width);
1284        }
1285
1286        if (height != -1) {
1287            mLastHeight = height;
1288            setHeight(height);
1289        }
1290
1291        if (!isShowing() || mContentView == null) {
1292            return;
1293        }
1294
1295        WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams();
1296
1297        boolean update = force;
1298
1299        final int finalWidth = mWidthMode < 0 ? mWidthMode : mLastWidth;
1300        if (width != -1 && p.width != finalWidth) {
1301            p.width = mLastWidth = finalWidth;
1302            update = true;
1303        }
1304
1305        final int finalHeight = mHeightMode < 0 ? mHeightMode : mLastHeight;
1306        if (height != -1 && p.height != finalHeight) {
1307            p.height = mLastHeight = finalHeight;
1308            update = true;
1309        }
1310
1311        if (p.x != x) {
1312            p.x = x;
1313            update = true;
1314        }
1315
1316        if (p.y != y) {
1317            p.y = y;
1318            update = true;
1319        }
1320
1321        final int newAnim = computeAnimationResource();
1322        if (newAnim != p.windowAnimations) {
1323            p.windowAnimations = newAnim;
1324            update = true;
1325        }
1326
1327        final int newFlags = computeFlags(p.flags);
1328        if (newFlags != p.flags) {
1329            p.flags = newFlags;
1330            update = true;
1331        }
1332
1333        if (update) {
1334            mWindowManager.updateViewLayout(mPopupView, p);
1335        }
1336    }
1337
1338    /**
1339     * <p>Updates the position and the dimension of the popup window. Calling this
1340     * function also updates the window with the current popup state as described
1341     * for {@link #update()}.</p>
1342     *
1343     * @param anchor the popup's anchor view
1344     * @param width the new width, can be -1 to ignore
1345     * @param height the new height, can be -1 to ignore
1346     */
1347    public void update(View anchor, int width, int height) {
1348        update(anchor, false, 0, 0, true, width, height);
1349    }
1350
1351    /**
1352     * <p>Updates the position and the dimension of the popup window. Width and
1353     * height can be set to -1 to update location only.  Calling this function
1354     * also updates the window with the current popup state as
1355     * described for {@link #update()}.</p>
1356     * <p>If the view later scrolls to move <code>anchor</code> to a different
1357     * location, the popup will be moved correspondingly.</p>
1358     *
1359     * @param anchor the popup's anchor view
1360     * @param xoff x offset from the view's left edge
1361     * @param yoff y offset from the view's bottom edge
1362     * @param width the new width, can be -1 to ignore
1363     * @param height the new height, can be -1 to ignore
1364     */
1365    public void update(View anchor, int xoff, int yoff, int width, int height) {
1366        update(anchor, true, xoff, yoff, true, width, height);
1367    }
1368
1369    private void update(View anchor, boolean updateLocation, int xoff, int yoff,
1370            boolean updateDimension, int width, int height) {
1371
1372        if (!isShowing() || mContentView == null) {
1373            return;
1374        }
1375
1376        WeakReference<View> oldAnchor = mAnchor;
1377        if (oldAnchor == null || oldAnchor.get() != anchor ||
1378                (updateLocation && (mAnchorXoff != xoff || mAnchorYoff != yoff))) {
1379            registerForScrollChanged(anchor, xoff, yoff);
1380        }
1381
1382        WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams();
1383
1384        if (updateDimension) {
1385            if (width == -1) {
1386                width = mPopupWidth;
1387            } else {
1388                mPopupWidth = width;
1389            }
1390            if (height == -1) {
1391                height = mPopupHeight;
1392            } else {
1393                mPopupHeight = height;
1394            }
1395        }
1396
1397        int x = p.x;
1398        int y = p.y;
1399
1400        if (updateLocation) {
1401            updateAboveAnchor(findDropDownPosition(anchor, p, xoff, yoff));
1402        } else {
1403            updateAboveAnchor(findDropDownPosition(anchor, p, mAnchorXoff, mAnchorYoff));
1404        }
1405
1406        update(p.x, p.y, width, height, x != p.x || y != p.y);
1407    }
1408
1409    /**
1410     * Listener that is called when this popup window is dismissed.
1411     */
1412    public interface OnDismissListener {
1413        /**
1414         * Called when this popup window is dismissed.
1415         */
1416        public void onDismiss();
1417    }
1418
1419    private void unregisterForScrollChanged() {
1420        WeakReference<View> anchorRef = mAnchor;
1421        View anchor = null;
1422        if (anchorRef != null) {
1423            anchor = anchorRef.get();
1424        }
1425        if (anchor != null) {
1426            ViewTreeObserver vto = anchor.getViewTreeObserver();
1427            vto.removeOnScrollChangedListener(mOnScrollChangedListener);
1428        }
1429        mAnchor = null;
1430    }
1431
1432    private void registerForScrollChanged(View anchor, int xoff, int yoff) {
1433        unregisterForScrollChanged();
1434
1435        mAnchor = new WeakReference<View>(anchor);
1436        ViewTreeObserver vto = anchor.getViewTreeObserver();
1437        if (vto != null) {
1438            vto.addOnScrollChangedListener(mOnScrollChangedListener);
1439        }
1440
1441        mAnchorXoff = xoff;
1442        mAnchorYoff = yoff;
1443    }
1444
1445    private class PopupViewContainer extends FrameLayout {
1446        private static final String TAG = "PopupWindow.PopupViewContainer";
1447
1448        public PopupViewContainer(Context context) {
1449            super(context);
1450        }
1451
1452        @Override
1453        protected int[] onCreateDrawableState(int extraSpace) {
1454            if (mAboveAnchor) {
1455                // 1 more needed for the above anchor state
1456                final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
1457                View.mergeDrawableStates(drawableState, ABOVE_ANCHOR_STATE_SET);
1458                return drawableState;
1459            } else {
1460                return super.onCreateDrawableState(extraSpace);
1461            }
1462        }
1463
1464        @Override
1465        public boolean dispatchKeyEvent(KeyEvent event) {
1466            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
1467                if (event.getAction() == KeyEvent.ACTION_DOWN
1468                        && event.getRepeatCount() == 0) {
1469                    getKeyDispatcherState().startTracking(event, this);
1470                    return true;
1471                } else if (event.getAction() == KeyEvent.ACTION_UP
1472                        && getKeyDispatcherState().isTracking(event) && !event.isCanceled()) {
1473                    dismiss();
1474                    return true;
1475                }
1476                return super.dispatchKeyEvent(event);
1477            } else {
1478                return super.dispatchKeyEvent(event);
1479            }
1480        }
1481
1482        @Override
1483        public boolean dispatchTouchEvent(MotionEvent ev) {
1484            if (mTouchInterceptor != null && mTouchInterceptor.onTouch(this, ev)) {
1485                return true;
1486            }
1487            return super.dispatchTouchEvent(ev);
1488        }
1489
1490        @Override
1491        public boolean onTouchEvent(MotionEvent event) {
1492            final int x = (int) event.getX();
1493            final int y = (int) event.getY();
1494
1495            if ((event.getAction() == MotionEvent.ACTION_DOWN)
1496                    && ((x < 0) || (x >= getWidth()) || (y < 0) || (y >= getHeight()))) {
1497                dismiss();
1498                return true;
1499            } else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
1500                dismiss();
1501                return true;
1502            } else {
1503                return super.onTouchEvent(event);
1504            }
1505        }
1506
1507        @Override
1508        public void sendAccessibilityEvent(int eventType) {
1509            // clinets are interested in the content not the container, make it event source
1510            if (mContentView != null) {
1511                mContentView.sendAccessibilityEvent(eventType);
1512            } else {
1513                super.sendAccessibilityEvent(eventType);
1514            }
1515        }
1516    }
1517
1518}
1519