ListPopupWindow.java revision 4267534d1c42af847ed0cefd1c88c99f66b36571
1/* 2 * Copyright (C) 2010 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 android.content.Context; 20import android.database.DataSetObserver; 21import android.graphics.Rect; 22import android.graphics.drawable.Drawable; 23import android.os.Handler; 24import android.util.AttributeSet; 25import android.util.Log; 26import android.view.KeyEvent; 27import android.view.MotionEvent; 28import android.view.View; 29import android.view.ViewGroup; 30import android.view.ViewParent; 31import android.view.View.MeasureSpec; 32import android.view.View.OnTouchListener; 33 34/** 35 * A ListPopupWindow anchors itself to a host view and displays a 36 * list of choices. When one is selected, the popup is dismissed. 37 * 38 * <p>ListPopupWindow contains a number of tricky behaviors surrounding 39 * positioning, scrolling parents to fit the dropdown, interacting 40 * sanely with the IME if present, and others. 41 * 42 * @see android.widget.AutoCompleteTextView 43 * @see android.widget.Spinner 44 */ 45public class ListPopupWindow { 46 private static final String TAG = "ListPopupWindow"; 47 private static final boolean DEBUG = false; 48 49 /** 50 * This value controls the length of time that the user 51 * must leave a pointer down without scrolling to expand 52 * the autocomplete dropdown list to cover the IME. 53 */ 54 private static final int EXPAND_LIST_TIMEOUT = 250; 55 56 private Context mContext; 57 private PopupWindow mPopup; 58 private ListAdapter mAdapter; 59 private DropDownListView mDropDownList; 60 61 private int mDropDownHeight = ViewGroup.LayoutParams.WRAP_CONTENT; 62 private int mDropDownWidth = ViewGroup.LayoutParams.WRAP_CONTENT; 63 private int mDropDownHorizontalOffset; 64 private int mDropDownVerticalOffset; 65 66 private boolean mDropDownAlwaysVisible = false; 67 private boolean mForceIgnoreOutsideTouch = false; 68 69 private View mPromptView; 70 private int mPromptPosition = POSITION_PROMPT_ABOVE; 71 72 private DataSetObserver mObserver; 73 74 private View mDropDownAnchorView; 75 76 private Drawable mDropDownListHighlight; 77 78 private AdapterView.OnItemClickListener mItemClickListener; 79 private AdapterView.OnItemSelectedListener mItemSelectedListener; 80 81 private final ResizePopupRunnable mResizePopupRunnable = new ResizePopupRunnable(); 82 private final PopupTouchInterceptor mTouchInterceptor = new PopupTouchInterceptor(); 83 private final PopupScrollListener mScrollListener = new PopupScrollListener(); 84 private final ListSelectorHider mHideSelector = new ListSelectorHider(); 85 private Runnable mShowDropDownRunnable; 86 87 private Handler mHandler = new Handler(); 88 89 private Rect mTempRect = new Rect(); 90 91 private boolean mModal; 92 93 /** 94 * The provided prompt view should appear above list content. 95 * 96 * @see #setPromptPosition(int) 97 * @see #getPromptPosition() 98 * @see #setPromptView(View) 99 */ 100 public static final int POSITION_PROMPT_ABOVE = 0; 101 102 /** 103 * The provided prompt view should appear below list content. 104 * 105 * @see #setPromptPosition(int) 106 * @see #getPromptPosition() 107 * @see #setPromptView(View) 108 */ 109 public static final int POSITION_PROMPT_BELOW = 1; 110 111 /** 112 * Alias for {@link ViewGroup.LayoutParams#MATCH_PARENT}. 113 * If used to specify a popup width, the popup will match the width of the anchor view. 114 * If used to specify a popup height, the popup will fill available space. 115 */ 116 public static final int MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT; 117 118 /** 119 * Alias for {@link ViewGroup.LayoutParams#WRAP_CONTENT}. 120 * If used to specify a popup width, the popup will use the width of its content. 121 */ 122 public static final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT; 123 124 /** 125 * Mode for {@link #setInputMethodMode(int)}: the requirements for the 126 * input method should be based on the focusability of the popup. That is 127 * if it is focusable than it needs to work with the input method, else 128 * it doesn't. 129 */ 130 public static final int INPUT_METHOD_FROM_FOCUSABLE = PopupWindow.INPUT_METHOD_FROM_FOCUSABLE; 131 132 /** 133 * Mode for {@link #setInputMethodMode(int)}: this popup always needs to 134 * work with an input method, regardless of whether it is focusable. This 135 * means that it will always be displayed so that the user can also operate 136 * the input method while it is shown. 137 */ 138 public static final int INPUT_METHOD_NEEDED = PopupWindow.INPUT_METHOD_NEEDED; 139 140 /** 141 * Mode for {@link #setInputMethodMode(int)}: this popup never needs to 142 * work with an input method, regardless of whether it is focusable. This 143 * means that it will always be displayed to use as much space on the 144 * screen as needed, regardless of whether this covers the input method. 145 */ 146 public static final int INPUT_METHOD_NOT_NEEDED = PopupWindow.INPUT_METHOD_NOT_NEEDED; 147 148 /** 149 * Create a new, empty popup window capable of displaying items from a ListAdapter. 150 * Backgrounds should be set using {@link #setBackgroundDrawable(Drawable)}. 151 * 152 * @param context Context used for contained views. 153 */ 154 public ListPopupWindow(Context context) { 155 this(context, null, 0, 0); 156 } 157 158 /** 159 * Create a new, empty popup window capable of displaying items from a ListAdapter. 160 * Backgrounds should be set using {@link #setBackgroundDrawable(Drawable)}. 161 * 162 * @param context Context used for contained views. 163 * @param attrs Attributes from inflating parent views used to style the popup. 164 */ 165 public ListPopupWindow(Context context, AttributeSet attrs) { 166 this(context, attrs, 0, 0); 167 } 168 169 /** 170 * Create a new, empty popup window capable of displaying items from a ListAdapter. 171 * Backgrounds should be set using {@link #setBackgroundDrawable(Drawable)}. 172 * 173 * @param context Context used for contained views. 174 * @param attrs Attributes from inflating parent views used to style the popup. 175 * @param defStyleAttr Default style attribute to use for popup content. 176 */ 177 public ListPopupWindow(Context context, AttributeSet attrs, int defStyleAttr) { 178 this(context, attrs, defStyleAttr, 0); 179 } 180 181 /** 182 * Create a new, empty popup window capable of displaying items from a ListAdapter. 183 * Backgrounds should be set using {@link #setBackgroundDrawable(Drawable)}. 184 * 185 * @param context Context used for contained views. 186 * @param attrs Attributes from inflating parent views used to style the popup. 187 * @param defStyleAttr Style attribute to read for default styling of popup content. 188 * @param defStyleRes Style resource ID to use for default styling of popup content. 189 */ 190 public ListPopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 191 mContext = context; 192 mPopup = new PopupWindow(context, attrs, defStyleAttr, defStyleRes); 193 } 194 195 /** 196 * Sets the adapter that provides the data and the views to represent the data 197 * in this popup window. 198 * 199 * @param adapter The adapter to use to create this window's content. 200 */ 201 public void setAdapter(ListAdapter adapter) { 202 if (mObserver == null) { 203 mObserver = new PopupDataSetObserver(); 204 } else if (mAdapter != null) { 205 mAdapter.unregisterDataSetObserver(mObserver); 206 } 207 mAdapter = adapter; 208 if (mAdapter != null) { 209 adapter.registerDataSetObserver(mObserver); 210 } 211 212 if (mDropDownList != null) { 213 mDropDownList.setAdapter(mAdapter); 214 } 215 } 216 217 /** 218 * Set where the optional prompt view should appear. The default is 219 * {@link #POSITION_PROMPT_ABOVE}. 220 * 221 * @param position A position constant declaring where the prompt should be displayed. 222 * 223 * @see #POSITION_PROMPT_ABOVE 224 * @see #POSITION_PROMPT_BELOW 225 */ 226 public void setPromptPosition(int position) { 227 mPromptPosition = position; 228 } 229 230 /** 231 * @return Where the optional prompt view should appear. 232 * 233 * @see #POSITION_PROMPT_ABOVE 234 * @see #POSITION_PROMPT_BELOW 235 */ 236 public int getPromptPosition() { 237 return mPromptPosition; 238 } 239 240 /** 241 * Set whether this window should be modal when shown. 242 * 243 * <p>If a popup window is modal, it will receive all touch and key input. 244 * If the user touches outside the popup window's content area the popup window 245 * will be dismissed. 246 * 247 * @param modal {@code true} if the popup window should be modal, {@code false} otherwise. 248 */ 249 public void setModal(boolean modal) { 250 mModal = true; 251 mPopup.setFocusable(modal); 252 } 253 254 /** 255 * Returns whether the popup window will be modal when shown. 256 * 257 * @return {@code true} if the popup window will be modal, {@code false} otherwise. 258 */ 259 public boolean isModal() { 260 return mModal; 261 } 262 263 /** 264 * Forces outside touches to be ignored. Normally if {@link #isDropDownAlwaysVisible()} is 265 * false, we allow outside touch to dismiss the dropdown. If this is set to true, then we 266 * ignore outside touch even when the drop down is not set to always visible. 267 * 268 * @hide Used only by AutoCompleteTextView to handle some internal special cases. 269 */ 270 public void setForceIgnoreOutsideTouch(boolean forceIgnoreOutsideTouch) { 271 mForceIgnoreOutsideTouch = forceIgnoreOutsideTouch; 272 } 273 274 /** 275 * Sets whether the drop-down should remain visible under certain conditions. 276 * 277 * The drop-down will occupy the entire screen below {@link #getAnchorView} regardless 278 * of the size or content of the list. {@link #getBackground()} will fill any space 279 * that is not used by the list. 280 * 281 * @param dropDownAlwaysVisible Whether to keep the drop-down visible. 282 * 283 * @hide Only used by AutoCompleteTextView under special conditions. 284 */ 285 public void setDropDownAlwaysVisible(boolean dropDownAlwaysVisible) { 286 mDropDownAlwaysVisible = dropDownAlwaysVisible; 287 } 288 289 /** 290 * @return Whether the drop-down is visible under special conditions. 291 * 292 * @hide Only used by AutoCompleteTextView under special conditions. 293 */ 294 public boolean isDropDownAlwaysVisible() { 295 return mDropDownAlwaysVisible; 296 } 297 298 /** 299 * Sets the operating mode for the soft input area. 300 * 301 * @param mode The desired mode, see 302 * {@link android.view.WindowManager.LayoutParams#softInputMode} 303 * for the full list 304 * 305 * @see android.view.WindowManager.LayoutParams#softInputMode 306 * @see #getSoftInputMode() 307 */ 308 public void setSoftInputMode(int mode) { 309 mPopup.setSoftInputMode(mode); 310 } 311 312 /** 313 * Returns the current value in {@link #setSoftInputMode(int)}. 314 * 315 * @see #setSoftInputMode(int) 316 * @see android.view.WindowManager.LayoutParams#softInputMode 317 */ 318 public int getSoftInputMode() { 319 return mPopup.getSoftInputMode(); 320 } 321 322 /** 323 * Sets a drawable to use as the list item selector. 324 * 325 * @param selector List selector drawable to use in the popup. 326 */ 327 public void setListSelector(Drawable selector) { 328 mDropDownListHighlight = selector; 329 } 330 331 /** 332 * @return The background drawable for the popup window. 333 */ 334 public Drawable getBackground() { 335 return mPopup.getBackground(); 336 } 337 338 /** 339 * Sets a drawable to be the background for the popup window. 340 * 341 * @param d A drawable to set as the background. 342 */ 343 public void setBackgroundDrawable(Drawable d) { 344 mPopup.setBackgroundDrawable(d); 345 } 346 347 /** 348 * Set an animation style to use when the popup window is shown or dismissed. 349 * 350 * @param animationStyle Animation style to use. 351 */ 352 public void setAnimationStyle(int animationStyle) { 353 mPopup.setAnimationStyle(animationStyle); 354 } 355 356 /** 357 * Returns the animation style that will be used when the popup window is 358 * shown or dismissed. 359 * 360 * @return Animation style that will be used. 361 */ 362 public int getAnimationStyle() { 363 return mPopup.getAnimationStyle(); 364 } 365 366 /** 367 * Returns the view that will be used to anchor this popup. 368 * 369 * @return The popup's anchor view 370 */ 371 public View getAnchorView() { 372 return mDropDownAnchorView; 373 } 374 375 /** 376 * Sets the popup's anchor view. This popup will always be positioned relative to 377 * the anchor view when shown. 378 * 379 * @param anchor The view to use as an anchor. 380 */ 381 public void setAnchorView(View anchor) { 382 mDropDownAnchorView = anchor; 383 } 384 385 /** 386 * @return The horizontal offset of the popup from its anchor in pixels. 387 */ 388 public int getHorizontalOffset() { 389 return mDropDownHorizontalOffset; 390 } 391 392 /** 393 * Set the horizontal offset of this popup from its anchor view in pixels. 394 * 395 * @param offset The horizontal offset of the popup from its anchor. 396 */ 397 public void setHorizontalOffset(int offset) { 398 mDropDownHorizontalOffset = offset; 399 } 400 401 /** 402 * @return The vertical offset of the popup from its anchor in pixels. 403 */ 404 public int getVerticalOffset() { 405 return mDropDownVerticalOffset; 406 } 407 408 /** 409 * Set the vertical offset of this popup from its anchor view in pixels. 410 * 411 * @param offset The vertical offset of the popup from its anchor. 412 */ 413 public void setVerticalOffset(int offset) { 414 mDropDownVerticalOffset = offset; 415 } 416 417 /** 418 * @return The width of the popup window in pixels. 419 */ 420 public int getWidth() { 421 return mDropDownWidth; 422 } 423 424 /** 425 * Sets the width of the popup window in pixels. Can also be {@link #MATCH_PARENT} 426 * or {@link #WRAP_CONTENT}. 427 * 428 * @param width Width of the popup window. 429 */ 430 public void setWidth(int width) { 431 mDropDownWidth = width; 432 } 433 434 /** 435 * Sets the width of the popup window by the size of its content. The final width may be 436 * larger to accommodate styled window dressing. 437 * 438 * @param width Desired width of content in pixels. 439 */ 440 public void setContentWidth(int width) { 441 Drawable popupBackground = mPopup.getBackground(); 442 if (popupBackground != null) { 443 mDropDownWidth = popupBackground.getIntrinsicWidth() + width; 444 } 445 } 446 447 /** 448 * @return The height of the popup window in pixels. 449 */ 450 public int getHeight() { 451 return mDropDownHeight; 452 } 453 454 /** 455 * Sets the height of the popup window in pixels. Can also be {@link #MATCH_PARENT}. 456 * 457 * @param height Height of the popup window. 458 */ 459 public void setHeight(int height) { 460 mDropDownHeight = height; 461 } 462 463 /** 464 * Sets a listener to receive events when a list item is clicked. 465 * 466 * @param clickListener Listener to register 467 * 468 * @see ListView#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener) 469 */ 470 public void setOnItemClickListener(AdapterView.OnItemClickListener clickListener) { 471 mItemClickListener = clickListener; 472 } 473 474 /** 475 * Sets a listener to receive events when a list item is selected. 476 * 477 * @param selectedListener Listener to register. 478 * 479 * @see ListView#setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener) 480 */ 481 public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener selectedListener) { 482 mItemSelectedListener = selectedListener; 483 } 484 485 /** 486 * Set a view to act as a user prompt for this popup window. Where the prompt view will appear 487 * is controlled by {@link #setPromptPosition(int)}. 488 * 489 * @param prompt View to use as an informational prompt. 490 */ 491 public void setPromptView(View prompt) { 492 boolean showing = isShowing(); 493 if (showing) { 494 removePromptView(); 495 } 496 mPromptView = prompt; 497 if (showing) { 498 show(); 499 } 500 } 501 502 /** 503 * Post a {@link #show()} call to the UI thread. 504 */ 505 public void postShow() { 506 mHandler.post(mShowDropDownRunnable); 507 } 508 509 /** 510 * Show the popup list. If the list is already showing, this method 511 * will recalculate the popup's size and position. 512 */ 513 public void show() { 514 int height = buildDropDown(); 515 516 int widthSpec = 0; 517 int heightSpec = 0; 518 519 boolean noInputMethod = isInputMethodNotNeeded(); 520 521 if (mPopup.isShowing()) { 522 if (mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT) { 523 // The call to PopupWindow's update method below can accept -1 for any 524 // value you do not want to update. 525 widthSpec = -1; 526 } else if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { 527 widthSpec = getAnchorView().getWidth(); 528 } else { 529 widthSpec = mDropDownWidth; 530 } 531 532 if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { 533 // The call to PopupWindow's update method below can accept -1 for any 534 // value you do not want to update. 535 heightSpec = noInputMethod ? height : ViewGroup.LayoutParams.MATCH_PARENT; 536 if (noInputMethod) { 537 mPopup.setWindowLayoutMode( 538 mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT ? 539 ViewGroup.LayoutParams.MATCH_PARENT : 0, 0); 540 } else { 541 mPopup.setWindowLayoutMode( 542 mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT ? 543 ViewGroup.LayoutParams.MATCH_PARENT : 0, 544 ViewGroup.LayoutParams.MATCH_PARENT); 545 } 546 } else if (mDropDownHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { 547 heightSpec = height; 548 } else { 549 heightSpec = mDropDownHeight; 550 } 551 552 mPopup.setOutsideTouchable(!mForceIgnoreOutsideTouch && !mDropDownAlwaysVisible); 553 554 mPopup.update(getAnchorView(), mDropDownHorizontalOffset, 555 mDropDownVerticalOffset, widthSpec, heightSpec); 556 } else { 557 if (mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT) { 558 widthSpec = ViewGroup.LayoutParams.MATCH_PARENT; 559 } else { 560 if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { 561 mPopup.setWidth(getAnchorView().getWidth()); 562 } else { 563 mPopup.setWidth(mDropDownWidth); 564 } 565 } 566 567 if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { 568 heightSpec = ViewGroup.LayoutParams.MATCH_PARENT; 569 } else { 570 if (mDropDownHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { 571 mPopup.setHeight(height); 572 } else { 573 mPopup.setHeight(mDropDownHeight); 574 } 575 } 576 577 mPopup.setWindowLayoutMode(widthSpec, heightSpec); 578 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); 579 580 // use outside touchable to dismiss drop down when touching outside of it, so 581 // only set this if the dropdown is not always visible 582 mPopup.setOutsideTouchable(!mForceIgnoreOutsideTouch && !mDropDownAlwaysVisible); 583 mPopup.setTouchInterceptor(mTouchInterceptor); 584 mPopup.showAsDropDown(getAnchorView(), 585 mDropDownHorizontalOffset, mDropDownVerticalOffset); 586 mDropDownList.setSelection(ListView.INVALID_POSITION); 587 588 if (!mModal || mDropDownList.isInTouchMode()) { 589 clearListSelection(); 590 } 591 if (!mModal) { 592 mHandler.post(mHideSelector); 593 } 594 } 595 } 596 597 /** 598 * Dismiss the popup window. 599 */ 600 public void dismiss() { 601 mPopup.dismiss(); 602 removePromptView(); 603 mPopup.setContentView(null); 604 mDropDownList = null; 605 } 606 607 private void removePromptView() { 608 if (mPromptView != null) { 609 final ViewParent parent = mPromptView.getParent(); 610 if (parent instanceof ViewGroup) { 611 final ViewGroup group = (ViewGroup) parent; 612 group.removeView(mPromptView); 613 } 614 } 615 } 616 617 /** 618 * Control how the popup operates with an input method: one of 619 * {@link #INPUT_METHOD_FROM_FOCUSABLE}, {@link #INPUT_METHOD_NEEDED}, 620 * or {@link #INPUT_METHOD_NOT_NEEDED}. 621 * 622 * <p>If the popup is showing, calling this method will take effect only 623 * the next time the popup is shown or through a manual call to the {@link #show()} 624 * method.</p> 625 * 626 * @see #getInputMethodMode() 627 * @see #show() 628 */ 629 public void setInputMethodMode(int mode) { 630 mPopup.setInputMethodMode(mode); 631 } 632 633 /** 634 * Return the current value in {@link #setInputMethodMode(int)}. 635 * 636 * @see #setInputMethodMode(int) 637 */ 638 public int getInputMethodMode() { 639 return mPopup.getInputMethodMode(); 640 } 641 642 /** 643 * Set the selected position of the list. 644 * Only valid when {@link #isShowing()} == {@code true}. 645 * 646 * @param position List position to set as selected. 647 */ 648 public void setSelection(int position) { 649 DropDownListView list = mDropDownList; 650 if (isShowing() && list != null) { 651 list.mListSelectionHidden = false; 652 list.setSelection(position); 653 if (list.getChoiceMode() != ListView.CHOICE_MODE_NONE) { 654 list.setItemChecked(position, true); 655 } 656 } 657 } 658 659 /** 660 * Clear any current list selection. 661 * Only valid when {@link #isShowing()} == {@code true}. 662 */ 663 public void clearListSelection() { 664 final DropDownListView list = mDropDownList; 665 if (list != null) { 666 // WARNING: Please read the comment where mListSelectionHidden is declared 667 list.mListSelectionHidden = true; 668 list.hideSelector(); 669 list.requestLayout(); 670 } 671 } 672 673 /** 674 * @return {@code true} if the popup is currently showing, {@code false} otherwise. 675 */ 676 public boolean isShowing() { 677 return mPopup.isShowing(); 678 } 679 680 /** 681 * @return {@code true} if this popup is configured to assume the user does not need 682 * to interact with the IME while it is showing, {@code false} otherwise. 683 */ 684 public boolean isInputMethodNotNeeded() { 685 return mPopup.getInputMethodMode() == INPUT_METHOD_NOT_NEEDED; 686 } 687 688 /** 689 * Perform an item click operation on the specified list adapter position. 690 * 691 * @param position Adapter position for performing the click 692 * @return true if the click action could be performed, false if not. 693 * (e.g. if the popup was not showing, this method would return false.) 694 */ 695 public boolean performItemClick(int position) { 696 if (isShowing()) { 697 if (mItemClickListener != null) { 698 final DropDownListView list = mDropDownList; 699 final View child = list.getChildAt(position - list.getFirstVisiblePosition()); 700 mItemClickListener.onItemClick(list, child, position, child.getId()); 701 } 702 return true; 703 } 704 return false; 705 } 706 707 /** 708 * @return The currently selected item or null if the popup is not showing. 709 */ 710 public Object getSelectedItem() { 711 if (!isShowing()) { 712 return null; 713 } 714 return mDropDownList.getSelectedItem(); 715 } 716 717 /** 718 * @return The position of the currently selected item or {@link ListView#INVALID_POSITION} 719 * if {@link #isShowing()} == {@code false}. 720 * 721 * @see ListView#getSelectedItemPosition() 722 */ 723 public int getSelectedItemPosition() { 724 if (!isShowing()) { 725 return ListView.INVALID_POSITION; 726 } 727 return mDropDownList.getSelectedItemPosition(); 728 } 729 730 /** 731 * @return The ID of the currently selected item or {@link ListView#INVALID_ROW_ID} 732 * if {@link #isShowing()} == {@code false}. 733 * 734 * @see ListView#getSelectedItemId() 735 */ 736 public long getSelectedItemId() { 737 if (!isShowing()) { 738 return ListView.INVALID_ROW_ID; 739 } 740 return mDropDownList.getSelectedItemId(); 741 } 742 743 /** 744 * @return The View for the currently selected item or null if 745 * {@link #isShowing()} == {@code false}. 746 * 747 * @see ListView#getSelectedView() 748 */ 749 public View getSelectedView() { 750 if (!isShowing()) { 751 return null; 752 } 753 return mDropDownList.getSelectedView(); 754 } 755 756 /** 757 * @return The {@link ListView} displayed within the popup window. 758 * Only valid when {@link #isShowing()} == {@code true}. 759 */ 760 public ListView getListView() { 761 return mDropDownList; 762 } 763 764 /** 765 * Filter key down events. By forwarding key up events to this function, 766 * views using non-modal ListPopupWindow can have it handle key selection of items. 767 * 768 * @param keyCode keyCode param passed to the host view's onKeyDown 769 * @param event event param passed to the host view's onKeyDown 770 * @return true if the event was handled, false if it was ignored. 771 * 772 * @see #setModal(boolean) 773 */ 774 public boolean onKeyDown(int keyCode, KeyEvent event) { 775 // when the drop down is shown, we drive it directly 776 if (isShowing()) { 777 // the key events are forwarded to the list in the drop down view 778 // note that ListView handles space but we don't want that to happen 779 // also if selection is not currently in the drop down, then don't 780 // let center or enter presses go there since that would cause it 781 // to select one of its items 782 if (keyCode != KeyEvent.KEYCODE_SPACE 783 && (mDropDownList.getSelectedItemPosition() >= 0 784 || (keyCode != KeyEvent.KEYCODE_ENTER 785 && keyCode != KeyEvent.KEYCODE_DPAD_CENTER))) { 786 int curIndex = mDropDownList.getSelectedItemPosition(); 787 boolean consumed; 788 789 final boolean below = !mPopup.isAboveAnchor(); 790 791 final ListAdapter adapter = mAdapter; 792 793 boolean allEnabled; 794 int firstItem = Integer.MAX_VALUE; 795 int lastItem = Integer.MIN_VALUE; 796 797 if (adapter != null) { 798 allEnabled = adapter.areAllItemsEnabled(); 799 firstItem = allEnabled ? 0 : 800 mDropDownList.lookForSelectablePosition(0, true); 801 lastItem = allEnabled ? adapter.getCount() - 1 : 802 mDropDownList.lookForSelectablePosition(adapter.getCount() - 1, false); 803 } 804 805 if ((below && keyCode == KeyEvent.KEYCODE_DPAD_UP && curIndex <= firstItem) || 806 (!below && keyCode == KeyEvent.KEYCODE_DPAD_DOWN && curIndex >= lastItem)) { 807 // When the selection is at the top, we block the key 808 // event to prevent focus from moving. 809 clearListSelection(); 810 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); 811 show(); 812 return true; 813 } else { 814 // WARNING: Please read the comment where mListSelectionHidden 815 // is declared 816 mDropDownList.mListSelectionHidden = false; 817 } 818 819 consumed = mDropDownList.onKeyDown(keyCode, event); 820 if (DEBUG) Log.v(TAG, "Key down: code=" + keyCode + " list consumed=" + consumed); 821 822 if (consumed) { 823 // If it handled the key event, then the user is 824 // navigating in the list, so we should put it in front. 825 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 826 // Here's a little trick we need to do to make sure that 827 // the list view is actually showing its focus indicator, 828 // by ensuring it has focus and getting its window out 829 // of touch mode. 830 mDropDownList.requestFocusFromTouch(); 831 show(); 832 833 switch (keyCode) { 834 // avoid passing the focus from the text view to the 835 // next component 836 case KeyEvent.KEYCODE_ENTER: 837 case KeyEvent.KEYCODE_DPAD_CENTER: 838 case KeyEvent.KEYCODE_DPAD_DOWN: 839 case KeyEvent.KEYCODE_DPAD_UP: 840 return true; 841 } 842 } else { 843 if (below && keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { 844 // when the selection is at the bottom, we block the 845 // event to avoid going to the next focusable widget 846 if (curIndex == lastItem) { 847 return true; 848 } 849 } else if (!below && keyCode == KeyEvent.KEYCODE_DPAD_UP && 850 curIndex == firstItem) { 851 return true; 852 } 853 } 854 } 855 } 856 857 return false; 858 } 859 860 /** 861 * Filter key down events. By forwarding key up events to this function, 862 * views using non-modal ListPopupWindow can have it handle key selection of items. 863 * 864 * @param keyCode keyCode param passed to the host view's onKeyUp 865 * @param event event param passed to the host view's onKeyUp 866 * @return true if the event was handled, false if it was ignored. 867 * 868 * @see #setModal(boolean) 869 */ 870 public boolean onKeyUp(int keyCode, KeyEvent event) { 871 if (isShowing() && mDropDownList.getSelectedItemPosition() >= 0) { 872 boolean consumed = mDropDownList.onKeyUp(keyCode, event); 873 if (consumed) { 874 switch (keyCode) { 875 // if the list accepts the key events and the key event 876 // was a click, the text view gets the selected item 877 // from the drop down as its content 878 case KeyEvent.KEYCODE_ENTER: 879 case KeyEvent.KEYCODE_DPAD_CENTER: 880 dismiss(); 881 break; 882 } 883 } 884 return consumed; 885 } 886 return false; 887 } 888 889 /** 890 * Filter pre-IME key events. By forwarding {@link View#onKeyPreIme(int, KeyEvent)} 891 * events to this function, views using ListPopupWindow can have it dismiss the popup 892 * when the back key is pressed. 893 * 894 * @param keyCode keyCode param passed to the host view's onKeyPreIme 895 * @param event event param passed to the host view's onKeyPreIme 896 * @return true if the event was handled, false if it was ignored. 897 * 898 * @see #setModal(boolean) 899 */ 900 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 901 if (keyCode == KeyEvent.KEYCODE_BACK && isShowing()) { 902 // special case for the back key, we do not even try to send it 903 // to the drop down list but instead, consume it immediately 904 final View anchorView = mDropDownAnchorView; 905 if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { 906 anchorView.getKeyDispatcherState().startTracking(event, this); 907 return true; 908 } else if (event.getAction() == KeyEvent.ACTION_UP) { 909 anchorView.getKeyDispatcherState().handleUpEvent(event); 910 if (event.isTracking() && !event.isCanceled()) { 911 dismiss(); 912 return true; 913 } 914 } 915 } 916 return false; 917 } 918 919 /** 920 * <p>Builds the popup window's content and returns the height the popup 921 * should have. Returns -1 when the content already exists.</p> 922 * 923 * @return the content's height or -1 if content already exists 924 */ 925 private int buildDropDown() { 926 ViewGroup dropDownView; 927 int otherHeights = 0; 928 929 if (mDropDownList == null) { 930 Context context = mContext; 931 932 /** 933 * This Runnable exists for the sole purpose of checking if the view layout has got 934 * completed and if so call showDropDown to display the drop down. This is used to show 935 * the drop down as soon as possible after user opens up the search dialog, without 936 * waiting for the normal UI pipeline to do it's job which is slower than this method. 937 */ 938 mShowDropDownRunnable = new Runnable() { 939 public void run() { 940 // View layout should be all done before displaying the drop down. 941 View view = getAnchorView(); 942 if (view != null && view.getWindowToken() != null) { 943 show(); 944 } 945 } 946 }; 947 948 mDropDownList = new DropDownListView(context, !mModal); 949 if (mDropDownListHighlight != null) { 950 mDropDownList.setSelector(mDropDownListHighlight); 951 } 952 mDropDownList.setAdapter(mAdapter); 953 mDropDownList.setVerticalFadingEdgeEnabled(true); 954 mDropDownList.setOnItemClickListener(mItemClickListener); 955 mDropDownList.setFocusable(true); 956 mDropDownList.setFocusableInTouchMode(true); 957 mDropDownList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 958 public void onItemSelected(AdapterView<?> parent, View view, 959 int position, long id) { 960 961 if (position != -1) { 962 DropDownListView dropDownList = mDropDownList; 963 964 if (dropDownList != null) { 965 dropDownList.mListSelectionHidden = false; 966 } 967 } 968 } 969 970 public void onNothingSelected(AdapterView<?> parent) { 971 } 972 }); 973 mDropDownList.setOnScrollListener(mScrollListener); 974 975 if (mItemSelectedListener != null) { 976 mDropDownList.setOnItemSelectedListener(mItemSelectedListener); 977 } 978 979 dropDownView = mDropDownList; 980 981 View hintView = mPromptView; 982 if (hintView != null) { 983 // if an hint has been specified, we accomodate more space for it and 984 // add a text view in the drop down menu, at the bottom of the list 985 LinearLayout hintContainer = new LinearLayout(context); 986 hintContainer.setOrientation(LinearLayout.VERTICAL); 987 988 LinearLayout.LayoutParams hintParams = new LinearLayout.LayoutParams( 989 ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f 990 ); 991 992 switch (mPromptPosition) { 993 case POSITION_PROMPT_BELOW: 994 hintContainer.addView(dropDownView, hintParams); 995 hintContainer.addView(hintView); 996 break; 997 998 case POSITION_PROMPT_ABOVE: 999 hintContainer.addView(hintView); 1000 hintContainer.addView(dropDownView, hintParams); 1001 break; 1002 1003 default: 1004 Log.e(TAG, "Invalid hint position " + mPromptPosition); 1005 break; 1006 } 1007 1008 // measure the hint's height to find how much more vertical space 1009 // we need to add to the drop down's height 1010 int widthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.AT_MOST); 1011 int heightSpec = MeasureSpec.UNSPECIFIED; 1012 hintView.measure(widthSpec, heightSpec); 1013 1014 hintParams = (LinearLayout.LayoutParams) hintView.getLayoutParams(); 1015 otherHeights = hintView.getMeasuredHeight() + hintParams.topMargin 1016 + hintParams.bottomMargin; 1017 1018 dropDownView = hintContainer; 1019 } 1020 1021 mPopup.setContentView(dropDownView); 1022 } else { 1023 dropDownView = (ViewGroup) mPopup.getContentView(); 1024 final View view = mPromptView; 1025 if (view != null) { 1026 LinearLayout.LayoutParams hintParams = 1027 (LinearLayout.LayoutParams) view.getLayoutParams(); 1028 otherHeights = view.getMeasuredHeight() + hintParams.topMargin 1029 + hintParams.bottomMargin; 1030 } 1031 } 1032 1033 // Max height available on the screen for a popup. 1034 boolean ignoreBottomDecorations = 1035 mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED; 1036 final int maxHeight = mPopup.getMaxAvailableHeight( 1037 getAnchorView(), mDropDownVerticalOffset, ignoreBottomDecorations); 1038 1039 // getMaxAvailableHeight() subtracts the padding, so we put it back, 1040 // to get the available height for the whole window 1041 int padding = 0; 1042 Drawable background = mPopup.getBackground(); 1043 if (background != null) { 1044 background.getPadding(mTempRect); 1045 padding = mTempRect.top + mTempRect.bottom; 1046 } 1047 1048 if (mDropDownAlwaysVisible || mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { 1049 return maxHeight + padding; 1050 } 1051 1052 final int listContent = mDropDownList.measureHeightOfChildren(MeasureSpec.UNSPECIFIED, 1053 0, ListView.NO_POSITION, maxHeight - otherHeights, 2); 1054 // add padding only if the list has items in it, that way we don't show 1055 // the popup if it is not needed 1056 if (listContent > 0) otherHeights += padding; 1057 1058 return listContent + otherHeights; 1059 } 1060 1061 /** 1062 * <p>Wrapper class for a ListView. This wrapper can hijack the focus to 1063 * make sure the list uses the appropriate drawables and states when 1064 * displayed on screen within a drop down. The focus is never actually 1065 * passed to the drop down in this mode; the list only looks focused.</p> 1066 */ 1067 private static class DropDownListView extends ListView { 1068 private static final String TAG = ListPopupWindow.TAG + ".DropDownListView"; 1069 /* 1070 * WARNING: This is a workaround for a touch mode issue. 1071 * 1072 * Touch mode is propagated lazily to windows. This causes problems in 1073 * the following scenario: 1074 * - Type something in the AutoCompleteTextView and get some results 1075 * - Move down with the d-pad to select an item in the list 1076 * - Move up with the d-pad until the selection disappears 1077 * - Type more text in the AutoCompleteTextView *using the soft keyboard* 1078 * and get new results; you are now in touch mode 1079 * - The selection comes back on the first item in the list, even though 1080 * the list is supposed to be in touch mode 1081 * 1082 * Using the soft keyboard triggers the touch mode change but that change 1083 * is propagated to our window only after the first list layout, therefore 1084 * after the list attempts to resurrect the selection. 1085 * 1086 * The trick to work around this issue is to pretend the list is in touch 1087 * mode when we know that the selection should not appear, that is when 1088 * we know the user moved the selection away from the list. 1089 * 1090 * This boolean is set to true whenever we explicitly hide the list's 1091 * selection and reset to false whenever we know the user moved the 1092 * selection back to the list. 1093 * 1094 * When this boolean is true, isInTouchMode() returns true, otherwise it 1095 * returns super.isInTouchMode(). 1096 */ 1097 private boolean mListSelectionHidden; 1098 1099 /** 1100 * True if this wrapper should fake focus. 1101 */ 1102 private boolean mHijackFocus; 1103 1104 /** 1105 * <p>Creates a new list view wrapper.</p> 1106 * 1107 * @param context this view's context 1108 */ 1109 public DropDownListView(Context context, boolean hijackFocus) { 1110 super(context, null, com.android.internal.R.attr.dropDownListViewStyle); 1111 mHijackFocus = hijackFocus; 1112 } 1113 1114 /** 1115 * <p>Avoids jarring scrolling effect by ensuring that list elements 1116 * made of a text view fit on a single line.</p> 1117 * 1118 * @param position the item index in the list to get a view for 1119 * @return the view for the specified item 1120 */ 1121 @Override 1122 View obtainView(int position, boolean[] isScrap) { 1123 View view = super.obtainView(position, isScrap); 1124 1125 if (view instanceof TextView) { 1126 ((TextView) view).setHorizontallyScrolling(true); 1127 } 1128 1129 return view; 1130 } 1131 1132 @Override 1133 public boolean isInTouchMode() { 1134 // WARNING: Please read the comment where mListSelectionHidden is declared 1135 return (mHijackFocus && mListSelectionHidden) || super.isInTouchMode(); 1136 } 1137 1138 /** 1139 * <p>Returns the focus state in the drop down.</p> 1140 * 1141 * @return true always if hijacking focus 1142 */ 1143 @Override 1144 public boolean hasWindowFocus() { 1145 return mHijackFocus || super.hasWindowFocus(); 1146 } 1147 1148 /** 1149 * <p>Returns the focus state in the drop down.</p> 1150 * 1151 * @return true always if hijacking focus 1152 */ 1153 @Override 1154 public boolean isFocused() { 1155 return mHijackFocus || super.isFocused(); 1156 } 1157 1158 /** 1159 * <p>Returns the focus state in the drop down.</p> 1160 * 1161 * @return true always if hijacking focus 1162 */ 1163 @Override 1164 public boolean hasFocus() { 1165 return mHijackFocus || super.hasFocus(); 1166 } 1167 } 1168 1169 private class PopupDataSetObserver extends DataSetObserver { 1170 @Override 1171 public void onChanged() { 1172 if (isShowing()) { 1173 // Resize the popup to fit new content 1174 show(); 1175 } 1176 } 1177 1178 @Override 1179 public void onInvalidated() { 1180 dismiss(); 1181 } 1182 } 1183 1184 private class ListSelectorHider implements Runnable { 1185 public void run() { 1186 clearListSelection(); 1187 } 1188 } 1189 1190 private class ResizePopupRunnable implements Runnable { 1191 public void run() { 1192 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 1193 show(); 1194 } 1195 } 1196 1197 private class PopupTouchInterceptor implements OnTouchListener { 1198 public boolean onTouch(View v, MotionEvent event) { 1199 final int action = event.getAction(); 1200 final int x = (int) event.getX(); 1201 final int y = (int) event.getY(); 1202 1203 if (action == MotionEvent.ACTION_DOWN && 1204 mPopup != null && mPopup.isShowing() && 1205 (x >= 0 && x < getWidth() && y >= 0 && y < getHeight())) { 1206 mHandler.postDelayed(mResizePopupRunnable, EXPAND_LIST_TIMEOUT); 1207 } else if (action == MotionEvent.ACTION_UP) { 1208 mHandler.removeCallbacks(mResizePopupRunnable); 1209 } 1210 return false; 1211 } 1212 } 1213 1214 private class PopupScrollListener implements ListView.OnScrollListener { 1215 public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, 1216 int totalItemCount) { 1217 1218 } 1219 1220 public void onScrollStateChanged(AbsListView view, int scrollState) { 1221 if (scrollState == SCROLL_STATE_TOUCH_SCROLL && 1222 !isInputMethodNotNeeded() && mPopup.getContentView() != null) { 1223 mHandler.removeCallbacks(mResizePopupRunnable); 1224 mResizePopupRunnable.run(); 1225 } 1226 } 1227 } 1228} 1229