ListPopupWindow.java revision c3fa6304c997ccecf8ed15a4cbb7bd245128f3c3
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 adapter.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 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 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 * @return The height of the popup window in pixels. 436 */ 437 public int getHeight() { 438 return mDropDownHeight; 439 } 440 441 /** 442 * Sets the height of the popup window in pixels. Can also be {@link #MATCH_PARENT}. 443 * 444 * @param height Height of the popup window. 445 */ 446 public void setHeight(int height) { 447 mDropDownHeight = height; 448 } 449 450 /** 451 * Sets a listener to receive events when a list item is clicked. 452 * 453 * @param clickListener Listener to register 454 * 455 * @see ListView#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener) 456 */ 457 public void setOnItemClickListener(AdapterView.OnItemClickListener clickListener) { 458 mItemClickListener = clickListener; 459 } 460 461 /** 462 * Sets a listener to receive events when a list item is selected. 463 * 464 * @param selectedListener Listener to register. 465 * 466 * @see ListView#setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener) 467 */ 468 public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener selectedListener) { 469 mItemSelectedListener = selectedListener; 470 } 471 472 /** 473 * Set a view to act as a user prompt for this popup window. Where the prompt view will appear 474 * is controlled by {@link #setPromptPosition(int)}. 475 * 476 * @param prompt View to use as an informational prompt. 477 */ 478 public void setPromptView(View prompt) { 479 boolean showing = isShowing(); 480 if (showing) { 481 removePromptView(); 482 } 483 mPromptView = prompt; 484 if (showing) { 485 show(); 486 } 487 } 488 489 /** 490 * Post a {@link #show()} call to the UI thread. 491 */ 492 public void postShow() { 493 mHandler.post(mShowDropDownRunnable); 494 } 495 496 /** 497 * Show the popup list. If the list is already showing, this method 498 * will recalculate the popup's size and position. 499 */ 500 public void show() { 501 int height = buildDropDown(); 502 503 int widthSpec = 0; 504 int heightSpec = 0; 505 506 boolean noInputMethod = isInputMethodNotNeeded(); 507 508 if (mPopup.isShowing()) { 509 if (mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT) { 510 // The call to PopupWindow's update method below can accept -1 for any 511 // value you do not want to update. 512 widthSpec = -1; 513 } else if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { 514 widthSpec = getAnchorView().getWidth(); 515 } else { 516 widthSpec = mDropDownWidth; 517 } 518 519 if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { 520 // The call to PopupWindow's update method below can accept -1 for any 521 // value you do not want to update. 522 heightSpec = noInputMethod ? height : ViewGroup.LayoutParams.MATCH_PARENT; 523 if (noInputMethod) { 524 mPopup.setWindowLayoutMode( 525 mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT ? 526 ViewGroup.LayoutParams.MATCH_PARENT : 0, 0); 527 } else { 528 mPopup.setWindowLayoutMode( 529 mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT ? 530 ViewGroup.LayoutParams.MATCH_PARENT : 0, 531 ViewGroup.LayoutParams.MATCH_PARENT); 532 } 533 } else if (mDropDownHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { 534 heightSpec = height; 535 } else { 536 heightSpec = mDropDownHeight; 537 } 538 539 mPopup.setOutsideTouchable(!mForceIgnoreOutsideTouch && !mDropDownAlwaysVisible); 540 541 mPopup.update(getAnchorView(), mDropDownHorizontalOffset, 542 mDropDownVerticalOffset, widthSpec, heightSpec); 543 } else { 544 if (mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT) { 545 widthSpec = ViewGroup.LayoutParams.MATCH_PARENT; 546 } else { 547 if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { 548 mPopup.setWidth(getAnchorView().getWidth()); 549 } else { 550 mPopup.setWidth(mDropDownWidth); 551 } 552 } 553 554 if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { 555 heightSpec = ViewGroup.LayoutParams.MATCH_PARENT; 556 } else { 557 if (mDropDownHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { 558 mPopup.setHeight(height); 559 } else { 560 mPopup.setHeight(mDropDownHeight); 561 } 562 } 563 564 mPopup.setWindowLayoutMode(widthSpec, heightSpec); 565 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); 566 567 // use outside touchable to dismiss drop down when touching outside of it, so 568 // only set this if the dropdown is not always visible 569 mPopup.setOutsideTouchable(!mForceIgnoreOutsideTouch && !mDropDownAlwaysVisible); 570 mPopup.setTouchInterceptor(mTouchInterceptor); 571 mPopup.showAsDropDown(getAnchorView(), 572 mDropDownHorizontalOffset, mDropDownVerticalOffset); 573 mDropDownList.setSelection(ListView.INVALID_POSITION); 574 575 if (!mModal || mDropDownList.isInTouchMode()) { 576 clearListSelection(); 577 } 578 if (!mModal) { 579 mHandler.post(mHideSelector); 580 } 581 } 582 } 583 584 /** 585 * Dismiss the popup window. 586 */ 587 public void dismiss() { 588 mPopup.dismiss(); 589 removePromptView(); 590 mPopup.setContentView(null); 591 mDropDownList = null; 592 } 593 594 private void removePromptView() { 595 if (mPromptView != null) { 596 final ViewParent parent = mPromptView.getParent(); 597 if (parent instanceof ViewGroup) { 598 final ViewGroup group = (ViewGroup) parent; 599 group.removeView(mPromptView); 600 } 601 } 602 } 603 604 /** 605 * Control how the popup operates with an input method: one of 606 * {@link #INPUT_METHOD_FROM_FOCUSABLE}, {@link #INPUT_METHOD_NEEDED}, 607 * or {@link #INPUT_METHOD_NOT_NEEDED}. 608 * 609 * <p>If the popup is showing, calling this method will take effect only 610 * the next time the popup is shown or through a manual call to the {@link #show()} 611 * method.</p> 612 * 613 * @see #getInputMethodMode() 614 * @see #show() 615 */ 616 public void setInputMethodMode(int mode) { 617 mPopup.setInputMethodMode(mode); 618 } 619 620 /** 621 * Return the current value in {@link #setInputMethodMode(int)}. 622 * 623 * @see #setInputMethodMode(int) 624 */ 625 public int getInputMethodMode() { 626 return mPopup.getInputMethodMode(); 627 } 628 629 /** 630 * Set the selected position of the list. 631 * Only valid when {@link #isShowing()} == {@code true}. 632 * 633 * @param position List position to set as selected. 634 */ 635 public void setSelection(int position) { 636 DropDownListView list = mDropDownList; 637 if (isShowing() && list != null) { 638 list.mListSelectionHidden = false; 639 list.setSelection(position); 640 if (list.getChoiceMode() != ListView.CHOICE_MODE_NONE) { 641 list.setItemChecked(position, true); 642 } 643 } 644 } 645 646 /** 647 * Clear any current list selection. 648 * Only valid when {@link #isShowing()} == {@code true}. 649 */ 650 public void clearListSelection() { 651 final DropDownListView list = mDropDownList; 652 if (list != null) { 653 // WARNING: Please read the comment where mListSelectionHidden is declared 654 list.mListSelectionHidden = true; 655 list.hideSelector(); 656 list.requestLayout(); 657 } 658 } 659 660 /** 661 * @return {@code true} if the popup is currently showing, {@code false} otherwise. 662 */ 663 public boolean isShowing() { 664 return mPopup.isShowing(); 665 } 666 667 /** 668 * @return {@code true} if this popup is configured to assume the user does not need 669 * to interact with the IME while it is showing, {@code false} otherwise. 670 */ 671 public boolean isInputMethodNotNeeded() { 672 return mPopup.getInputMethodMode() == INPUT_METHOD_NOT_NEEDED; 673 } 674 675 /** 676 * Perform an item click operation on the specified list adapter position. 677 * 678 * @param position Adapter position for performing the click 679 * @return true if the click action could be performed, false if not. 680 * (e.g. if the popup was not showing, this method would return false.) 681 */ 682 public boolean performItemClick(int position) { 683 if (isShowing()) { 684 if (mItemClickListener != null) { 685 final DropDownListView list = mDropDownList; 686 final View child = list.getChildAt(position - list.getFirstVisiblePosition()); 687 mItemClickListener.onItemClick(list, child, position, child.getId()); 688 } 689 return true; 690 } 691 return false; 692 } 693 694 /** 695 * @return The currently selected item or null if the popup is not showing. 696 */ 697 public Object getSelectedItem() { 698 if (!isShowing()) { 699 return null; 700 } 701 return mDropDownList.getSelectedItem(); 702 } 703 704 /** 705 * @return The position of the currently selected item or {@link ListView#INVALID_POSITION} 706 * if {@link #isShowing()} == {@code false}. 707 * 708 * @see ListView#getSelectedItemPosition() 709 */ 710 public int getSelectedItemPosition() { 711 if (!isShowing()) { 712 return ListView.INVALID_POSITION; 713 } 714 return mDropDownList.getSelectedItemPosition(); 715 } 716 717 /** 718 * @return The ID of the currently selected item or {@link ListView#INVALID_ROW_ID} 719 * if {@link #isShowing()} == {@code false}. 720 * 721 * @see ListView#getSelectedItemId() 722 */ 723 public long getSelectedItemId() { 724 if (!isShowing()) { 725 return ListView.INVALID_ROW_ID; 726 } 727 return mDropDownList.getSelectedItemId(); 728 } 729 730 /** 731 * @return The View for the currently selected item or null if 732 * {@link #isShowing()} == {@code false}. 733 * 734 * @see ListView#getSelectedView() 735 */ 736 public View getSelectedView() { 737 if (!isShowing()) { 738 return null; 739 } 740 return mDropDownList.getSelectedView(); 741 } 742 743 /** 744 * @return The {@link ListView} displayed within the popup window. 745 * Only valid when {@link #isShowing()} == {@code true}. 746 */ 747 public ListView getListView() { 748 return mDropDownList; 749 } 750 751 /** 752 * Filter key down events. By forwarding key up events to this function, 753 * views using non-modal ListPopupWindow can have it handle key selection of items. 754 * 755 * @param keyCode keyCode param passed to the host view's onKeyDown 756 * @param event event param passed to the host view's onKeyDown 757 * @return true if the event was handled, false if it was ignored. 758 * 759 * @see #setModal(boolean) 760 */ 761 public boolean onKeyDown(int keyCode, KeyEvent event) { 762 // when the drop down is shown, we drive it directly 763 if (isShowing()) { 764 // the key events are forwarded to the list in the drop down view 765 // note that ListView handles space but we don't want that to happen 766 // also if selection is not currently in the drop down, then don't 767 // let center or enter presses go there since that would cause it 768 // to select one of its items 769 if (keyCode != KeyEvent.KEYCODE_SPACE 770 && (mDropDownList.getSelectedItemPosition() >= 0 771 || (keyCode != KeyEvent.KEYCODE_ENTER 772 && keyCode != KeyEvent.KEYCODE_DPAD_CENTER))) { 773 int curIndex = mDropDownList.getSelectedItemPosition(); 774 boolean consumed; 775 776 final boolean below = !mPopup.isAboveAnchor(); 777 778 final ListAdapter adapter = mAdapter; 779 780 boolean allEnabled; 781 int firstItem = Integer.MAX_VALUE; 782 int lastItem = Integer.MIN_VALUE; 783 784 if (adapter != null) { 785 allEnabled = adapter.areAllItemsEnabled(); 786 firstItem = allEnabled ? 0 : 787 mDropDownList.lookForSelectablePosition(0, true); 788 lastItem = allEnabled ? adapter.getCount() - 1 : 789 mDropDownList.lookForSelectablePosition(adapter.getCount() - 1, false); 790 } 791 792 if ((below && keyCode == KeyEvent.KEYCODE_DPAD_UP && curIndex <= firstItem) || 793 (!below && keyCode == KeyEvent.KEYCODE_DPAD_DOWN && curIndex >= lastItem)) { 794 // When the selection is at the top, we block the key 795 // event to prevent focus from moving. 796 clearListSelection(); 797 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); 798 show(); 799 return true; 800 } else { 801 // WARNING: Please read the comment where mListSelectionHidden 802 // is declared 803 mDropDownList.mListSelectionHidden = false; 804 } 805 806 consumed = mDropDownList.onKeyDown(keyCode, event); 807 if (DEBUG) Log.v(TAG, "Key down: code=" + keyCode + " list consumed=" + consumed); 808 809 if (consumed) { 810 // If it handled the key event, then the user is 811 // navigating in the list, so we should put it in front. 812 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 813 // Here's a little trick we need to do to make sure that 814 // the list view is actually showing its focus indicator, 815 // by ensuring it has focus and getting its window out 816 // of touch mode. 817 mDropDownList.requestFocusFromTouch(); 818 show(); 819 820 switch (keyCode) { 821 // avoid passing the focus from the text view to the 822 // next component 823 case KeyEvent.KEYCODE_ENTER: 824 case KeyEvent.KEYCODE_DPAD_CENTER: 825 case KeyEvent.KEYCODE_DPAD_DOWN: 826 case KeyEvent.KEYCODE_DPAD_UP: 827 return true; 828 } 829 } else { 830 if (below && keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { 831 // when the selection is at the bottom, we block the 832 // event to avoid going to the next focusable widget 833 if (curIndex == lastItem) { 834 return true; 835 } 836 } else if (!below && keyCode == KeyEvent.KEYCODE_DPAD_UP && 837 curIndex == firstItem) { 838 return true; 839 } 840 } 841 } 842 } 843 844 return false; 845 } 846 847 /** 848 * Filter key down events. By forwarding key up events to this function, 849 * views using non-modal ListPopupWindow can have it handle key selection of items. 850 * 851 * @param keyCode keyCode param passed to the host view's onKeyUp 852 * @param event event param passed to the host view's onKeyUp 853 * @return true if the event was handled, false if it was ignored. 854 * 855 * @see #setModal(boolean) 856 */ 857 public boolean onKeyUp(int keyCode, KeyEvent event) { 858 if (isShowing() && mDropDownList.getSelectedItemPosition() >= 0) { 859 boolean consumed = mDropDownList.onKeyUp(keyCode, event); 860 if (consumed) { 861 switch (keyCode) { 862 // if the list accepts the key events and the key event 863 // was a click, the text view gets the selected item 864 // from the drop down as its content 865 case KeyEvent.KEYCODE_ENTER: 866 case KeyEvent.KEYCODE_DPAD_CENTER: 867 dismiss(); 868 break; 869 } 870 } 871 return consumed; 872 } 873 return false; 874 } 875 876 /** 877 * Filter pre-IME key events. By forwarding {@link View#onKeyPreIme(int, KeyEvent)} 878 * events to this function, views using ListPopupWindow can have it dismiss the popup 879 * when the back key is pressed. 880 * 881 * @param keyCode keyCode param passed to the host view's onKeyPreIme 882 * @param event event param passed to the host view's onKeyPreIme 883 * @return true if the event was handled, false if it was ignored. 884 * 885 * @see #setModal(boolean) 886 */ 887 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 888 if (keyCode == KeyEvent.KEYCODE_BACK && isShowing()) { 889 // special case for the back key, we do not even try to send it 890 // to the drop down list but instead, consume it immediately 891 final View anchorView = mDropDownAnchorView; 892 if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { 893 anchorView.getKeyDispatcherState().startTracking(event, this); 894 return true; 895 } else if (event.getAction() == KeyEvent.ACTION_UP) { 896 anchorView.getKeyDispatcherState().handleUpEvent(event); 897 if (event.isTracking() && !event.isCanceled()) { 898 dismiss(); 899 return true; 900 } 901 } 902 } 903 return false; 904 } 905 906 /** 907 * <p>Builds the popup window's content and returns the height the popup 908 * should have. Returns -1 when the content already exists.</p> 909 * 910 * @return the content's height or -1 if content already exists 911 */ 912 private int buildDropDown() { 913 ViewGroup dropDownView; 914 int otherHeights = 0; 915 916 if (mDropDownList == null) { 917 Context context = mContext; 918 919 /** 920 * This Runnable exists for the sole purpose of checking if the view layout has got 921 * completed and if so call showDropDown to display the drop down. This is used to show 922 * the drop down as soon as possible after user opens up the search dialog, without 923 * waiting for the normal UI pipeline to do it's job which is slower than this method. 924 */ 925 mShowDropDownRunnable = new Runnable() { 926 public void run() { 927 // View layout should be all done before displaying the drop down. 928 View view = getAnchorView(); 929 if (view != null && view.getWindowToken() != null) { 930 show(); 931 } 932 } 933 }; 934 935 mDropDownList = new DropDownListView(context, !mModal); 936 if (mDropDownListHighlight != null) { 937 mDropDownList.setSelector(mDropDownListHighlight); 938 } 939 mDropDownList.setAdapter(mAdapter); 940 mDropDownList.setVerticalFadingEdgeEnabled(true); 941 mDropDownList.setOnItemClickListener(mItemClickListener); 942 mDropDownList.setFocusable(true); 943 mDropDownList.setFocusableInTouchMode(true); 944 mDropDownList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 945 public void onItemSelected(AdapterView<?> parent, View view, 946 int position, long id) { 947 948 if (position != -1) { 949 DropDownListView dropDownList = mDropDownList; 950 951 if (dropDownList != null) { 952 dropDownList.mListSelectionHidden = false; 953 } 954 } 955 } 956 957 public void onNothingSelected(AdapterView<?> parent) { 958 } 959 }); 960 mDropDownList.setOnScrollListener(mScrollListener); 961 962 if (mItemSelectedListener != null) { 963 mDropDownList.setOnItemSelectedListener(mItemSelectedListener); 964 } 965 966 dropDownView = mDropDownList; 967 968 View hintView = mPromptView; 969 if (hintView != null) { 970 // if an hint has been specified, we accomodate more space for it and 971 // add a text view in the drop down menu, at the bottom of the list 972 LinearLayout hintContainer = new LinearLayout(context); 973 hintContainer.setOrientation(LinearLayout.VERTICAL); 974 975 LinearLayout.LayoutParams hintParams = new LinearLayout.LayoutParams( 976 ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f 977 ); 978 979 switch (mPromptPosition) { 980 case POSITION_PROMPT_BELOW: 981 hintContainer.addView(dropDownView, hintParams); 982 hintContainer.addView(hintView); 983 break; 984 985 case POSITION_PROMPT_ABOVE: 986 hintContainer.addView(hintView); 987 hintContainer.addView(dropDownView, hintParams); 988 break; 989 990 default: 991 Log.e(TAG, "Invalid hint position " + mPromptPosition); 992 break; 993 } 994 995 // measure the hint's height to find how much more vertical space 996 // we need to add to the drop down's height 997 int widthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.AT_MOST); 998 int heightSpec = MeasureSpec.UNSPECIFIED; 999 hintView.measure(widthSpec, heightSpec); 1000 1001 hintParams = (LinearLayout.LayoutParams) hintView.getLayoutParams(); 1002 otherHeights = hintView.getMeasuredHeight() + hintParams.topMargin 1003 + hintParams.bottomMargin; 1004 1005 dropDownView = hintContainer; 1006 } 1007 1008 mPopup.setContentView(dropDownView); 1009 } else { 1010 dropDownView = (ViewGroup) mPopup.getContentView(); 1011 final View view = mPromptView; 1012 if (view != null) { 1013 LinearLayout.LayoutParams hintParams = 1014 (LinearLayout.LayoutParams) view.getLayoutParams(); 1015 otherHeights = view.getMeasuredHeight() + hintParams.topMargin 1016 + hintParams.bottomMargin; 1017 } 1018 } 1019 1020 // Max height available on the screen for a popup. 1021 boolean ignoreBottomDecorations = 1022 mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED; 1023 final int maxHeight = mPopup.getMaxAvailableHeight( 1024 getAnchorView(), mDropDownVerticalOffset, ignoreBottomDecorations); 1025 1026 // getMaxAvailableHeight() subtracts the padding, so we put it back, 1027 // to get the available height for the whole window 1028 int padding = 0; 1029 Drawable background = mPopup.getBackground(); 1030 if (background != null) { 1031 background.getPadding(mTempRect); 1032 padding = mTempRect.top + mTempRect.bottom; 1033 } 1034 1035 if (mDropDownAlwaysVisible || mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { 1036 return maxHeight + padding; 1037 } 1038 1039 final int listContent = mDropDownList.measureHeightOfChildren(MeasureSpec.UNSPECIFIED, 1040 0, ListView.NO_POSITION, maxHeight - otherHeights, 2); 1041 // add padding only if the list has items in it, that way we don't show 1042 // the popup if it is not needed 1043 if (listContent > 0) otherHeights += padding; 1044 1045 return listContent + otherHeights; 1046 } 1047 1048 /** 1049 * <p>Wrapper class for a ListView. This wrapper can hijack the focus to 1050 * make sure the list uses the appropriate drawables and states when 1051 * displayed on screen within a drop down. The focus is never actually 1052 * passed to the drop down in this mode; the list only looks focused.</p> 1053 */ 1054 private static class DropDownListView extends ListView { 1055 private static final String TAG = ListPopupWindow.TAG + ".DropDownListView"; 1056 /* 1057 * WARNING: This is a workaround for a touch mode issue. 1058 * 1059 * Touch mode is propagated lazily to windows. This causes problems in 1060 * the following scenario: 1061 * - Type something in the AutoCompleteTextView and get some results 1062 * - Move down with the d-pad to select an item in the list 1063 * - Move up with the d-pad until the selection disappears 1064 * - Type more text in the AutoCompleteTextView *using the soft keyboard* 1065 * and get new results; you are now in touch mode 1066 * - The selection comes back on the first item in the list, even though 1067 * the list is supposed to be in touch mode 1068 * 1069 * Using the soft keyboard triggers the touch mode change but that change 1070 * is propagated to our window only after the first list layout, therefore 1071 * after the list attempts to resurrect the selection. 1072 * 1073 * The trick to work around this issue is to pretend the list is in touch 1074 * mode when we know that the selection should not appear, that is when 1075 * we know the user moved the selection away from the list. 1076 * 1077 * This boolean is set to true whenever we explicitly hide the list's 1078 * selection and reset to false whenever we know the user moved the 1079 * selection back to the list. 1080 * 1081 * When this boolean is true, isInTouchMode() returns true, otherwise it 1082 * returns super.isInTouchMode(). 1083 */ 1084 private boolean mListSelectionHidden; 1085 1086 /** 1087 * True if this wrapper should fake focus. 1088 */ 1089 private boolean mHijackFocus; 1090 1091 /** 1092 * <p>Creates a new list view wrapper.</p> 1093 * 1094 * @param context this view's context 1095 */ 1096 public DropDownListView(Context context, boolean hijackFocus) { 1097 super(context, null, com.android.internal.R.attr.dropDownListViewStyle); 1098 mHijackFocus = hijackFocus; 1099 } 1100 1101 /** 1102 * <p>Avoids jarring scrolling effect by ensuring that list elements 1103 * made of a text view fit on a single line.</p> 1104 * 1105 * @param position the item index in the list to get a view for 1106 * @return the view for the specified item 1107 */ 1108 @Override 1109 View obtainView(int position, boolean[] isScrap) { 1110 View view = super.obtainView(position, isScrap); 1111 1112 if (view instanceof TextView) { 1113 ((TextView) view).setHorizontallyScrolling(true); 1114 } 1115 1116 return view; 1117 } 1118 1119 @Override 1120 public boolean isInTouchMode() { 1121 // WARNING: Please read the comment where mListSelectionHidden is declared 1122 return (mHijackFocus && mListSelectionHidden) || super.isInTouchMode(); 1123 } 1124 1125 /** 1126 * <p>Returns the focus state in the drop down.</p> 1127 * 1128 * @return true always if hijacking focus 1129 */ 1130 @Override 1131 public boolean hasWindowFocus() { 1132 return mHijackFocus || super.hasWindowFocus(); 1133 } 1134 1135 /** 1136 * <p>Returns the focus state in the drop down.</p> 1137 * 1138 * @return true always if hijacking focus 1139 */ 1140 @Override 1141 public boolean isFocused() { 1142 return mHijackFocus || super.isFocused(); 1143 } 1144 1145 /** 1146 * <p>Returns the focus state in the drop down.</p> 1147 * 1148 * @return true always if hijacking focus 1149 */ 1150 @Override 1151 public boolean hasFocus() { 1152 return mHijackFocus || super.hasFocus(); 1153 } 1154 } 1155 1156 private class PopupDataSetObserver extends DataSetObserver { 1157 @Override 1158 public void onChanged() { 1159 if (isShowing()) { 1160 // Resize the popup to fit new content 1161 show(); 1162 } 1163 } 1164 1165 @Override 1166 public void onInvalidated() { 1167 dismiss(); 1168 } 1169 } 1170 1171 private class ListSelectorHider implements Runnable { 1172 public void run() { 1173 clearListSelection(); 1174 } 1175 } 1176 1177 private class ResizePopupRunnable implements Runnable { 1178 public void run() { 1179 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 1180 show(); 1181 } 1182 } 1183 1184 private class PopupTouchInterceptor implements OnTouchListener { 1185 public boolean onTouch(View v, MotionEvent event) { 1186 final int action = event.getAction(); 1187 final int x = (int) event.getX(); 1188 final int y = (int) event.getY(); 1189 1190 if (action == MotionEvent.ACTION_DOWN && 1191 mPopup != null && mPopup.isShowing() && 1192 (x >= 0 && x < getWidth() && y >= 0 && y < getHeight())) { 1193 mHandler.postDelayed(mResizePopupRunnable, EXPAND_LIST_TIMEOUT); 1194 } else if (action == MotionEvent.ACTION_UP) { 1195 mHandler.removeCallbacks(mResizePopupRunnable); 1196 } 1197 return false; 1198 } 1199 } 1200 1201 private class PopupScrollListener implements ListView.OnScrollListener { 1202 public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, 1203 int totalItemCount) { 1204 1205 } 1206 1207 public void onScrollStateChanged(AbsListView view, int scrollState) { 1208 if (scrollState == SCROLL_STATE_TOUCH_SCROLL && 1209 !isInputMethodNotNeeded() && mPopup.getContentView() != null) { 1210 mHandler.removeCallbacks(mResizePopupRunnable); 1211 mResizePopupRunnable.run(); 1212 } 1213 } 1214 } 1215} 1216