SearchView.java revision 79f7430bf93a9b5dc2b4e0f418f320affdfbf77b
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 static android.widget.SuggestionsAdapter.getColumnString; 20 21import com.android.internal.R; 22 23import android.app.PendingIntent; 24import android.app.SearchManager; 25import android.app.SearchableInfo; 26import android.content.ActivityNotFoundException; 27import android.content.ComponentName; 28import android.content.Context; 29import android.content.Intent; 30import android.content.pm.PackageManager; 31import android.content.pm.ResolveInfo; 32import android.content.res.Configuration; 33import android.content.res.Resources; 34import android.content.res.TypedArray; 35import android.database.Cursor; 36import android.graphics.Rect; 37import android.graphics.drawable.Drawable; 38import android.net.Uri; 39import android.os.Bundle; 40import android.speech.RecognizerIntent; 41import android.text.Editable; 42import android.text.TextUtils; 43import android.text.TextWatcher; 44import android.util.AttributeSet; 45import android.util.Log; 46import android.view.KeyEvent; 47import android.view.LayoutInflater; 48import android.view.View; 49import android.view.inputmethod.InputMethodManager; 50import android.widget.AdapterView.OnItemClickListener; 51import android.widget.AdapterView.OnItemSelectedListener; 52import android.widget.TextView.OnEditorActionListener; 53 54import java.util.WeakHashMap; 55 56/** 57 * Provides the user interface elements for the user to enter a search query and submit a 58 * request to a search provider. Shows a list of query suggestions or results, if 59 * available and allows the user to pick a suggestion or result to launch into. 60 * 61 * <p> 62 * <b>XML attributes</b> 63 * <p> 64 * See {@link android.R.styleable#SearchView SearchView Attributes}, 65 * {@link android.R.styleable#View View Attributes} 66 * 67 * @attr ref android.R.styleable#SearchView_iconifiedByDefault 68 * @attr ref android.R.styleable#SearchView_maxWidth 69 */ 70public class SearchView extends LinearLayout { 71 72 private static final boolean DBG = false; 73 private static final String LOG_TAG = "SearchView"; 74 75 private OnQueryTextListener mOnQueryChangeListener; 76 private OnCloseListener mOnCloseListener; 77 private OnFocusChangeListener mOnQueryTextFocusChangeListener; 78 private OnSuggestionListener mOnSuggestionListener; 79 private OnClickListener mOnSearchClickListener; 80 81 private boolean mIconifiedByDefault; 82 private boolean mIconified; 83 private CursorAdapter mSuggestionsAdapter; 84 private View mSearchButton; 85 private View mSubmitButton; 86 private View mSearchPlate; 87 private View mSubmitArea; 88 private ImageView mCloseButton; 89 private View mSearchEditFrame; 90 private View mVoiceButton; 91 private SearchAutoComplete mQueryTextView; 92 private boolean mSubmitButtonEnabled; 93 private CharSequence mQueryHint; 94 private boolean mQueryRefinement; 95 private boolean mClearingFocus; 96 private int mMaxWidth; 97 private boolean mVoiceButtonEnabled; 98 99 private SearchableInfo mSearchable; 100 private Bundle mAppSearchData; 101 102 // For voice searching 103 private final Intent mVoiceWebSearchIntent; 104 private final Intent mVoiceAppSearchIntent; 105 106 // A weak map of drawables we've gotten from other packages, so we don't load them 107 // more than once. 108 private final WeakHashMap<String, Drawable.ConstantState> mOutsideDrawablesCache = 109 new WeakHashMap<String, Drawable.ConstantState>(); 110 111 /** 112 * Callbacks for changes to the query text. 113 */ 114 public interface OnQueryTextListener { 115 116 /** 117 * Called when the user submits the query. This could be due to a key press on the 118 * keyboard or due to pressing a submit button. 119 * The listener can override the standard behavior by returning true 120 * to indicate that it has handled the submit request. Otherwise return false to 121 * let the SearchView handle the submission by launching any associated intent. 122 * 123 * @param query the query text that is to be submitted 124 * 125 * @return true if the query has been handled by the listener, false to let the 126 * SearchView perform the default action. 127 */ 128 boolean onQueryTextSubmit(String query); 129 130 /** 131 * Called when the query text is changed by the user. 132 * 133 * @param newText the new content of the query text field. 134 * 135 * @return false if the SearchView should perform the default action of showing any 136 * suggestions if available, true if the action was handled by the listener. 137 */ 138 boolean onQueryTextChange(String newText); 139 } 140 141 public interface OnCloseListener { 142 143 /** 144 * The user is attempting to close the SearchView. 145 * 146 * @return true if the listener wants to override the default behavior of clearing the 147 * text field and dismissing it, false otherwise. 148 */ 149 boolean onClose(); 150 } 151 152 /** 153 * Callback interface for selection events on suggestions. These callbacks 154 * are only relevant when a SearchableInfo has been specified by {@link #setSearchableInfo}. 155 */ 156 public interface OnSuggestionListener { 157 158 /** 159 * Called when a suggestion was selected by navigating to it. 160 * @param position the absolute position in the list of suggestions. 161 * 162 * @return true if the listener handles the event and wants to override the default 163 * behavior of possibly rewriting the query based on the selected item, false otherwise. 164 */ 165 boolean onSuggestionSelect(int position); 166 167 /** 168 * Called when a suggestion was clicked. 169 * @param position the absolute position of the clicked item in the list of suggestions. 170 * 171 * @return true if the listener handles the event and wants to override the default 172 * behavior of launching any intent or submitting a search query specified on that item. 173 * Return false otherwise. 174 */ 175 boolean onSuggestionClick(int position); 176 } 177 178 public SearchView(Context context) { 179 this(context, null); 180 } 181 182 public SearchView(Context context, AttributeSet attrs) { 183 super(context, attrs); 184 185 LayoutInflater inflater = (LayoutInflater) context 186 .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 187 inflater.inflate(R.layout.search_view, this, true); 188 189 mSearchButton = findViewById(R.id.search_button); 190 mQueryTextView = (SearchAutoComplete) findViewById(R.id.search_src_text); 191 mQueryTextView.setSearchView(this); 192 193 mSearchEditFrame = findViewById(R.id.search_edit_frame); 194 mSearchPlate = findViewById(R.id.search_plate); 195 mSubmitArea = findViewById(R.id.submit_area); 196 mSubmitButton = findViewById(R.id.search_go_btn); 197 mCloseButton = (ImageView) findViewById(R.id.search_close_btn); 198 mVoiceButton = findViewById(R.id.search_voice_btn); 199 200 mSearchButton.setOnClickListener(mOnClickListener); 201 mCloseButton.setOnClickListener(mOnClickListener); 202 mSubmitButton.setOnClickListener(mOnClickListener); 203 mVoiceButton.setOnClickListener(mOnClickListener); 204 205 mQueryTextView.addTextChangedListener(mTextWatcher); 206 mQueryTextView.setOnEditorActionListener(mOnEditorActionListener); 207 mQueryTextView.setOnItemClickListener(mOnItemClickListener); 208 mQueryTextView.setOnItemSelectedListener(mOnItemSelectedListener); 209 mQueryTextView.setOnKeyListener(mTextKeyListener); 210 // Inform any listener of focus changes 211 mQueryTextView.setOnFocusChangeListener(new OnFocusChangeListener() { 212 213 public void onFocusChange(View v, boolean hasFocus) { 214 if (mOnQueryTextFocusChangeListener != null) { 215 mOnQueryTextFocusChangeListener.onFocusChange(SearchView.this, hasFocus); 216 } 217 } 218 }); 219 220 boolean focusable = true; 221 222 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SearchView, 0, 0); 223 setIconifiedByDefault(a.getBoolean(R.styleable.SearchView_iconifiedByDefault, true)); 224 int maxWidth = a.getDimensionPixelSize(R.styleable.SearchView_maxWidth, -1); 225 if (maxWidth != -1) { 226 setMaxWidth(maxWidth); 227 } 228 CharSequence queryHint = a.getText(R.styleable.SearchView_queryHint); 229 if (!TextUtils.isEmpty(queryHint)) { 230 setQueryHint(queryHint); 231 } 232 a.recycle(); 233 234 a = context.obtainStyledAttributes(attrs, R.styleable.View, 0, 0); 235 focusable = a.getBoolean(R.styleable.View_focusable, focusable); 236 a.recycle(); 237 setFocusable(focusable); 238 239 // Save voice intent for later queries/launching 240 mVoiceWebSearchIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); 241 mVoiceWebSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 242 mVoiceWebSearchIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 243 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH); 244 245 mVoiceAppSearchIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 246 mVoiceAppSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 247 248 updateViewsVisibility(mIconifiedByDefault); 249 } 250 251 /** 252 * Sets the SearchableInfo for this SearchView. Properties in the SearchableInfo are used 253 * to display labels, hints, suggestions, create intents for launching search results screens 254 * and controlling other affordances such as a voice button. 255 * 256 * @param searchable a SearchableInfo can be retrieved from the SearchManager, for a specific 257 * activity or a global search provider. 258 */ 259 public void setSearchableInfo(SearchableInfo searchable) { 260 mSearchable = searchable; 261 if (mSearchable != null) { 262 updateSearchAutoComplete(); 263 updateQueryHint(); 264 } 265 // Cache the voice search capability 266 mVoiceButtonEnabled = hasVoiceSearch(); 267 updateViewsVisibility(mIconifiedByDefault); 268 } 269 270 /** 271 * Sets the APP_DATA for legacy SearchDialog use. 272 * @param appSearchData bundle provided by the app when launching the search dialog 273 * @hide 274 */ 275 public void setAppSearchData(Bundle appSearchData) { 276 mAppSearchData = appSearchData; 277 } 278 279 /** @hide */ 280 @Override 281 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 282 // Don't accept focus if in the middle of clearing focus 283 if (mClearingFocus) return false; 284 // Check if SearchView is focusable. 285 if (!isFocusable()) return false; 286 // If it is not iconified, then give the focus to the text field 287 if (!isIconified()) { 288 boolean result = mQueryTextView.requestFocus(direction, previouslyFocusedRect); 289 if (result) updateViewsVisibility(false); 290 return result; 291 } else { 292 return super.requestFocus(direction, previouslyFocusedRect); 293 } 294 } 295 296 /** @hide */ 297 @Override 298 public void clearFocus() { 299 mClearingFocus = true; 300 super.clearFocus(); 301 mQueryTextView.clearFocus(); 302 setImeVisibility(false); 303 mClearingFocus = false; 304 updateViewsVisibility(mIconifiedByDefault); 305 } 306 307 /** 308 * Sets a listener for user actions within the SearchView. 309 * 310 * @param listener the listener object that receives callbacks when the user performs 311 * actions in the SearchView such as clicking on buttons or typing a query. 312 */ 313 public void setOnQueryTextListener(OnQueryTextListener listener) { 314 mOnQueryChangeListener = listener; 315 } 316 317 /** 318 * Sets a listener to inform when the user closes the SearchView. 319 * 320 * @param listener the listener to call when the user closes the SearchView. 321 */ 322 public void setOnCloseListener(OnCloseListener listener) { 323 mOnCloseListener = listener; 324 } 325 326 /** 327 * Sets a listener to inform when the focus of the query text field changes. 328 * 329 * @param listener the listener to inform of focus changes. 330 */ 331 public void setOnQueryTextFocusChangeListener(OnFocusChangeListener listener) { 332 mOnQueryTextFocusChangeListener = listener; 333 } 334 335 /** 336 * Sets a listener to inform when a suggestion is focused or clicked. 337 * 338 * @param listener the listener to inform of suggestion selection events. 339 */ 340 public void setOnSuggestionListener(OnSuggestionListener listener) { 341 mOnSuggestionListener = listener; 342 } 343 344 /** 345 * Sets a listener to inform when the search button is pressed. This is only 346 * relevant when the text field is not visible by default. Calling {@link #setIconified 347 * setIconified(false)} can also cause this listener to be informed. 348 * 349 * @param listener the listener to inform when the search button is clicked or 350 * the text field is programmatically de-iconified. 351 */ 352 public void setOnSearchClickListener(OnClickListener listener) { 353 mOnSearchClickListener = listener; 354 } 355 356 /** 357 * Returns the query string currently in the text field. 358 * 359 * @return the query string 360 */ 361 public CharSequence getQuery() { 362 return mQueryTextView.getText(); 363 } 364 365 /** 366 * Sets a query string in the text field and optionally submits the query as well. 367 * 368 * @param query the query string. This replaces any query text already present in the 369 * text field. 370 * @param submit whether to submit the query right now or only update the contents of 371 * text field. 372 */ 373 public void setQuery(CharSequence query, boolean submit) { 374 mQueryTextView.setText(query); 375 if (query != null) { 376 mQueryTextView.setSelection(query.length()); 377 } 378 379 // If the query is not empty and submit is requested, submit the query 380 if (submit && !TextUtils.isEmpty(query)) { 381 onSubmitQuery(); 382 } 383 } 384 385 /** 386 * Sets the hint text to display in the query text field. This overrides any hint specified 387 * in the SearchableInfo. 388 * 389 * @param hint the hint text to display 390 */ 391 public void setQueryHint(CharSequence hint) { 392 mQueryHint = hint; 393 updateQueryHint(); 394 } 395 396 /** 397 * Sets the default or resting state of the search field. If true, a single search icon is 398 * shown by default and expands to show the text field and other buttons when pressed. Also, 399 * if the default state is iconified, then it collapses to that state when the close button 400 * is pressed. Changes to this property will take effect immediately. 401 * 402 * <p>The default value is true.</p> 403 * 404 * @param iconified whether the search field should be iconified by default 405 */ 406 public void setIconifiedByDefault(boolean iconified) { 407 if (mIconifiedByDefault == iconified) return; 408 mIconifiedByDefault = iconified; 409 updateViewsVisibility(iconified); 410 } 411 412 /** 413 * Returns the default iconified state of the search field. 414 * @return 415 */ 416 public boolean isIconfiedByDefault() { 417 return mIconifiedByDefault; 418 } 419 420 /** 421 * Iconifies or expands the SearchView. Any query text is cleared when iconified. This is 422 * a temporary state and does not override the default iconified state set by 423 * {@link #setIconifiedByDefault(boolean)}. If the default state is iconified, then 424 * a false here will only be valid until the user closes the field. And if the default 425 * state is expanded, then a true here will only clear the text field and not close it. 426 * 427 * @param iconify a true value will collapse the SearchView to an icon, while a false will 428 * expand it. 429 */ 430 public void setIconified(boolean iconify) { 431 if (iconify) { 432 onCloseClicked(); 433 } else { 434 onSearchClicked(); 435 } 436 } 437 438 /** 439 * Returns the current iconified state of the SearchView. 440 * 441 * @return true if the SearchView is currently iconified, false if the search field is 442 * fully visible. 443 */ 444 public boolean isIconified() { 445 return mIconified; 446 } 447 448 /** 449 * Enables showing a submit button when the query is non-empty. In cases where the SearchView 450 * is being used to filter the contents of the current activity and doesn't launch a separate 451 * results activity, then the submit button should be disabled. 452 * 453 * @param enabled true to show a submit button for submitting queries, false if a submit 454 * button is not required. 455 */ 456 public void setSubmitButtonEnabled(boolean enabled) { 457 mSubmitButtonEnabled = enabled; 458 updateViewsVisibility(isIconified()); 459 } 460 461 /** 462 * Returns whether the submit button is enabled when necessary or never displayed. 463 * 464 * @return whether the submit button is enabled automatically when necessary 465 */ 466 public boolean isSubmitButtonEnabled() { 467 return mSubmitButtonEnabled; 468 } 469 470 /** 471 * Specifies if a query refinement button should be displayed alongside each suggestion 472 * or if it should depend on the flags set in the individual items retrieved from the 473 * suggestions provider. Clicking on the query refinement button will replace the text 474 * in the query text field with the text from the suggestion. This flag only takes effect 475 * if a SearchableInfo has been specified with {@link #setSearchableInfo(SearchableInfo)} 476 * and not when using a custom adapter. 477 * 478 * @param enable true if all items should have a query refinement button, false if only 479 * those items that have a query refinement flag set should have the button. 480 * 481 * @see SearchManager#SUGGEST_COLUMN_FLAGS 482 * @see SearchManager#FLAG_QUERY_REFINEMENT 483 */ 484 public void setQueryRefinementEnabled(boolean enable) { 485 mQueryRefinement = enable; 486 if (mSuggestionsAdapter instanceof SuggestionsAdapter) { 487 ((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement( 488 enable ? SuggestionsAdapter.REFINE_ALL : SuggestionsAdapter.REFINE_BY_ENTRY); 489 } 490 } 491 492 /** 493 * Returns whether query refinement is enabled for all items or only specific ones. 494 * @return true if enabled for all items, false otherwise. 495 */ 496 public boolean isQueryRefinementEnabled() { 497 return mQueryRefinement; 498 } 499 500 /** 501 * You can set a custom adapter if you wish. Otherwise the default adapter is used to 502 * display the suggestions from the suggestions provider associated with the SearchableInfo. 503 * 504 * @see #setSearchableInfo(SearchableInfo) 505 */ 506 public void setSuggestionsAdapter(CursorAdapter adapter) { 507 mSuggestionsAdapter = adapter; 508 509 mQueryTextView.setAdapter(mSuggestionsAdapter); 510 } 511 512 /** 513 * Returns the adapter used for suggestions, if any. 514 * @return the suggestions adapter 515 */ 516 public CursorAdapter getSuggestionsAdapter() { 517 return mSuggestionsAdapter; 518 } 519 520 /** 521 * Makes the view at most this many pixels wide 522 * 523 * @attr ref android.R.styleable#SearchView_maxWidth 524 */ 525 public void setMaxWidth(int maxpixels) { 526 mMaxWidth = maxpixels; 527 528 requestLayout(); 529 } 530 531 @Override 532 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 533 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 534 int width = MeasureSpec.getSize(widthMeasureSpec); 535 536 if ((widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.EXACTLY) && mMaxWidth > 0 537 && width > mMaxWidth) { 538 super.onMeasure(MeasureSpec.makeMeasureSpec(mMaxWidth, widthMode), heightMeasureSpec); 539 } else { 540 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 541 } 542 } 543 544 private void updateViewsVisibility(final boolean collapsed) { 545 mIconified = collapsed; 546 // Visibility of views that are visible when collapsed 547 final int visCollapsed = collapsed ? VISIBLE : GONE; 548 // Is there text in the query 549 final boolean hasText = !TextUtils.isEmpty(mQueryTextView.getText()); 550 551 mSearchButton.setVisibility(visCollapsed); 552 updateSubmitButton(hasText); 553 mSearchEditFrame.setVisibility(collapsed ? GONE : VISIBLE); 554 updateCloseButton(); 555 updateVoiceButton(!hasText); 556 updateSubmitArea(); 557 } 558 559 private boolean hasVoiceSearch() { 560 if (mSearchable != null && mSearchable.getVoiceSearchEnabled()) { 561 Intent testIntent = null; 562 if (mSearchable.getVoiceSearchLaunchWebSearch()) { 563 testIntent = mVoiceWebSearchIntent; 564 } else if (mSearchable.getVoiceSearchLaunchRecognizer()) { 565 testIntent = mVoiceAppSearchIntent; 566 } 567 if (testIntent != null) { 568 ResolveInfo ri = getContext().getPackageManager().resolveActivity(testIntent, 569 PackageManager.MATCH_DEFAULT_ONLY); 570 return ri != null; 571 } 572 } 573 return false; 574 } 575 576 private boolean isSubmitAreaEnabled() { 577 return (mSubmitButtonEnabled || mVoiceButtonEnabled) && !isIconified(); 578 } 579 580 private void updateSubmitButton(boolean hasText) { 581 int visibility = GONE; 582 if (isSubmitAreaEnabled() && hasFocus() && (hasText || !mVoiceButtonEnabled)) { 583 visibility = VISIBLE; 584 } 585 mSubmitButton.setVisibility(visibility); 586 } 587 588 private void updateSubmitArea() { 589 int visibility = GONE; 590 if (isSubmitAreaEnabled() 591 && (mSubmitButton.getVisibility() == VISIBLE 592 || mVoiceButton.getVisibility() == VISIBLE)) { 593 visibility = VISIBLE; 594 } 595 mSubmitArea.setVisibility(visibility); 596 } 597 598 private void updateCloseButton() { 599 final boolean hasText = !TextUtils.isEmpty(mQueryTextView.getText()); 600 // Should we show the close button? It is not shown if there's no focus, 601 // field is not iconified by default and there is no text in it. 602 final boolean showClose = hasText || mIconifiedByDefault || mQueryTextView.hasFocus(); 603 mCloseButton.setVisibility(showClose ? VISIBLE : INVISIBLE); 604 mCloseButton.getDrawable().setState(hasText ? ENABLED_STATE_SET : EMPTY_STATE_SET); 605 } 606 607 private void updateFocusedState(boolean focused) { 608 mSearchPlate.getBackground().setState(focused ? FOCUSED_STATE_SET : EMPTY_STATE_SET); 609 mSubmitArea.getBackground().setState(focused ? FOCUSED_STATE_SET : EMPTY_STATE_SET); 610 } 611 612 private void setImeVisibility(boolean visible) { 613 InputMethodManager imm = (InputMethodManager) 614 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 615 616 // We made sure the IME was displayed, so also make sure it is closed 617 // when we go away. 618 if (imm != null) { 619 if (visible) { 620 imm.showSoftInputUnchecked(0, null); 621 } else { 622 imm.hideSoftInputFromWindow(getWindowToken(), 0); 623 } 624 } 625 } 626 627 /** 628 * Called by the SuggestionsAdapter 629 * @hide 630 */ 631 /* package */void onQueryRefine(CharSequence queryText) { 632 setQuery(queryText); 633 } 634 635 private final OnClickListener mOnClickListener = new OnClickListener() { 636 637 public void onClick(View v) { 638 if (v == mSearchButton) { 639 onSearchClicked(); 640 } else if (v == mCloseButton) { 641 onCloseClicked(); 642 } else if (v == mSubmitButton) { 643 onSubmitQuery(); 644 } else if (v == mVoiceButton) { 645 onVoiceClicked(); 646 } 647 } 648 }; 649 650 /** 651 * Handles the key down event for dealing with action keys. 652 * 653 * @param keyCode This is the keycode of the typed key, and is the same value as 654 * found in the KeyEvent parameter. 655 * @param event The complete event record for the typed key 656 * 657 * @return true if the event was handled here, or false if not. 658 */ 659 @Override 660 public boolean onKeyDown(int keyCode, KeyEvent event) { 661 if (mSearchable == null) { 662 return false; 663 } 664 665 // if it's an action specified by the searchable activity, launch the 666 // entered query with the action key 667 SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode); 668 if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) { 669 launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView.getText() 670 .toString()); 671 return true; 672 } 673 674 return super.onKeyDown(keyCode, event); 675 } 676 677 /** 678 * React to the user typing "enter" or other hardwired keys while typing in 679 * the search box. This handles these special keys while the edit box has 680 * focus. 681 */ 682 View.OnKeyListener mTextKeyListener = new View.OnKeyListener() { 683 public boolean onKey(View v, int keyCode, KeyEvent event) { 684 // guard against possible race conditions 685 if (mSearchable == null) { 686 return false; 687 } 688 689 if (DBG) { 690 Log.d(LOG_TAG, "mTextListener.onKey(" + keyCode + "," + event + "), selection: " 691 + mQueryTextView.getListSelection()); 692 } 693 694 // If a suggestion is selected, handle enter, search key, and action keys 695 // as presses on the selected suggestion 696 if (mQueryTextView.isPopupShowing() 697 && mQueryTextView.getListSelection() != ListView.INVALID_POSITION) { 698 return onSuggestionsKey(v, keyCode, event); 699 } 700 701 // If there is text in the query box, handle enter, and action keys 702 // The search key is handled by the dialog's onKeyDown(). 703 if (!mQueryTextView.isEmpty() && event.hasNoModifiers()) { 704 if (event.getAction() == KeyEvent.ACTION_UP) { 705 if (keyCode == KeyEvent.KEYCODE_ENTER) { 706 v.cancelLongPress(); 707 708 // Launch as a regular search. 709 launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, mQueryTextView.getText() 710 .toString()); 711 return true; 712 } 713 } 714 if (event.getAction() == KeyEvent.ACTION_DOWN) { 715 SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode); 716 if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) { 717 launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView 718 .getText().toString()); 719 return true; 720 } 721 } 722 } 723 return false; 724 } 725 }; 726 727 /** 728 * React to the user typing while in the suggestions list. First, check for 729 * action keys. If not handled, try refocusing regular characters into the 730 * EditText. 731 */ 732 private boolean onSuggestionsKey(View v, int keyCode, KeyEvent event) { 733 // guard against possible race conditions (late arrival after dismiss) 734 if (mSearchable == null) { 735 return false; 736 } 737 if (mSuggestionsAdapter == null) { 738 return false; 739 } 740 if (event.getAction() == KeyEvent.ACTION_DOWN && event.hasNoModifiers()) { 741 // First, check for enter or search (both of which we'll treat as a 742 // "click") 743 if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH 744 || keyCode == KeyEvent.KEYCODE_TAB) { 745 int position = mQueryTextView.getListSelection(); 746 return onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null); 747 } 748 749 // Next, check for left/right moves, which we use to "return" the 750 // user to the edit view 751 if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { 752 // give "focus" to text editor, with cursor at the beginning if 753 // left key, at end if right key 754 // TODO: Reverse left/right for right-to-left languages, e.g. 755 // Arabic 756 int selPoint = (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) ? 0 : mQueryTextView 757 .length(); 758 mQueryTextView.setSelection(selPoint); 759 mQueryTextView.setListSelection(0); 760 mQueryTextView.clearListSelection(); 761 mQueryTextView.ensureImeVisible(true); 762 763 return true; 764 } 765 766 // Next, check for an "up and out" move 767 if (keyCode == KeyEvent.KEYCODE_DPAD_UP && 0 == mQueryTextView.getListSelection()) { 768 // TODO: restoreUserQuery(); 769 // let ACTV complete the move 770 return false; 771 } 772 773 // Next, check for an "action key" 774 SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode); 775 if ((actionKey != null) 776 && ((actionKey.getSuggestActionMsg() != null) || (actionKey 777 .getSuggestActionMsgColumn() != null))) { 778 // launch suggestion using action key column 779 int position = mQueryTextView.getListSelection(); 780 if (position != ListView.INVALID_POSITION) { 781 Cursor c = mSuggestionsAdapter.getCursor(); 782 if (c.moveToPosition(position)) { 783 final String actionMsg = getActionKeyMessage(c, actionKey); 784 if (actionMsg != null && (actionMsg.length() > 0)) { 785 return onItemClicked(position, keyCode, actionMsg); 786 } 787 } 788 } 789 } 790 } 791 return false; 792 } 793 794 /** 795 * For a given suggestion and a given cursor row, get the action message. If 796 * not provided by the specific row/column, also check for a single 797 * definition (for the action key). 798 * 799 * @param c The cursor providing suggestions 800 * @param actionKey The actionkey record being examined 801 * 802 * @return Returns a string, or null if no action key message for this 803 * suggestion 804 */ 805 private static String getActionKeyMessage(Cursor c, SearchableInfo.ActionKeyInfo actionKey) { 806 String result = null; 807 // check first in the cursor data, for a suggestion-specific message 808 final String column = actionKey.getSuggestActionMsgColumn(); 809 if (column != null) { 810 result = SuggestionsAdapter.getColumnString(c, column); 811 } 812 // If the cursor didn't give us a message, see if there's a single 813 // message defined 814 // for the actionkey (for all suggestions) 815 if (result == null) { 816 result = actionKey.getSuggestActionMsg(); 817 } 818 return result; 819 } 820 821 private void updateQueryHint() { 822 if (mQueryHint != null) { 823 mQueryTextView.setHint(mQueryHint); 824 } else if (mSearchable != null) { 825 CharSequence hint = null; 826 int hintId = mSearchable.getHintId(); 827 if (hintId != 0) { 828 hint = getContext().getString(hintId); 829 } 830 if (hint != null) { 831 mQueryTextView.setHint(hint); 832 } 833 } 834 } 835 836 /** 837 * Updates the auto-complete text view. 838 */ 839 private void updateSearchAutoComplete() { 840 // close any existing suggestions adapter 841 //closeSuggestionsAdapter(); 842 843 mQueryTextView.setDropDownAnimationStyle(0); // no animation 844 mQueryTextView.setThreshold(mSearchable.getSuggestThreshold()); 845 846 // attach the suggestions adapter, if suggestions are available 847 // The existence of a suggestions authority is the proxy for "suggestions available here" 848 if (mSearchable.getSuggestAuthority() != null) { 849 mSuggestionsAdapter = new SuggestionsAdapter(getContext(), 850 this, mSearchable, mOutsideDrawablesCache); 851 mQueryTextView.setAdapter(mSuggestionsAdapter); 852 ((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement( 853 mQueryRefinement ? SuggestionsAdapter.REFINE_ALL 854 : SuggestionsAdapter.REFINE_BY_ENTRY); 855 } 856 } 857 858 /** 859 * Update the visibility of the voice button. There are actually two voice search modes, 860 * either of which will activate the button. 861 * @param empty whether the search query text field is empty. If it is, then the other 862 * criteria apply to make the voice button visible. 863 */ 864 private void updateVoiceButton(boolean empty) { 865 int visibility = GONE; 866 if (mVoiceButtonEnabled && !isIconified() && (empty || !mSubmitButtonEnabled)) { 867 visibility = VISIBLE; 868 mSubmitButton.setVisibility(GONE); 869 } 870 mVoiceButton.setVisibility(visibility); 871 } 872 873 private final OnEditorActionListener mOnEditorActionListener = new OnEditorActionListener() { 874 875 /** 876 * Called when the input method default action key is pressed. 877 */ 878 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 879 onSubmitQuery(); 880 return true; 881 } 882 }; 883 884 private void onTextChanged(CharSequence newText) { 885 CharSequence text = mQueryTextView.getText(); 886 boolean hasText = !TextUtils.isEmpty(text); 887 if (isSubmitButtonEnabled()) { 888 updateSubmitButton(hasText); 889 } 890 updateVoiceButton(!hasText); 891 updateCloseButton(); 892 updateSubmitArea(); 893 if (mOnQueryChangeListener != null) { 894 mOnQueryChangeListener.onQueryTextChange(newText.toString()); 895 } 896 } 897 898 private void onSubmitQuery() { 899 CharSequence query = mQueryTextView.getText(); 900 if (!TextUtils.isEmpty(query)) { 901 if (mOnQueryChangeListener == null 902 || !mOnQueryChangeListener.onQueryTextSubmit(query.toString())) { 903 if (mSearchable != null) { 904 launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString()); 905 setImeVisibility(false); 906 } 907 dismissSuggestions(); 908 } 909 } 910 } 911 912 private void dismissSuggestions() { 913 mQueryTextView.dismissDropDown(); 914 } 915 916 private void onCloseClicked() { 917 if (mOnCloseListener == null || !mOnCloseListener.onClose()) { 918 CharSequence text = mQueryTextView.getText(); 919 if (TextUtils.isEmpty(text)) { 920 // query field already empty, hide the keyboard and remove focus 921 clearFocus(); 922 setImeVisibility(false); 923 } else { 924 mQueryTextView.setText(""); 925 } 926 updateViewsVisibility(mIconifiedByDefault); 927 if (mIconifiedByDefault) setImeVisibility(false); 928 } 929 } 930 931 private void onSearchClicked() { 932 updateViewsVisibility(false); 933 mQueryTextView.requestFocus(); 934 setImeVisibility(true); 935 if (mOnSearchClickListener != null) { 936 mOnSearchClickListener.onClick(this); 937 } 938 } 939 940 private void onVoiceClicked() { 941 // guard against possible race conditions 942 if (mSearchable == null) { 943 return; 944 } 945 SearchableInfo searchable = mSearchable; 946 try { 947 if (searchable.getVoiceSearchLaunchWebSearch()) { 948 Intent webSearchIntent = createVoiceWebSearchIntent(mVoiceWebSearchIntent, 949 searchable); 950 getContext().startActivity(webSearchIntent); 951 } else if (searchable.getVoiceSearchLaunchRecognizer()) { 952 Intent appSearchIntent = createVoiceAppSearchIntent(mVoiceAppSearchIntent, 953 searchable); 954 getContext().startActivity(appSearchIntent); 955 } 956 } catch (ActivityNotFoundException e) { 957 // Should not happen, since we check the availability of 958 // voice search before showing the button. But just in case... 959 Log.w(LOG_TAG, "Could not find voice search activity"); 960 } 961 } 962 963 void onTextFocusChanged() { 964 updateViewsVisibility(isIconified()); 965 updateFocusedState(mQueryTextView.hasFocus()); 966 } 967 968 private boolean onItemClicked(int position, int actionKey, String actionMsg) { 969 if (mOnSuggestionListener == null 970 || !mOnSuggestionListener.onSuggestionClick(position)) { 971 launchSuggestion(position, KeyEvent.KEYCODE_UNKNOWN, null); 972 setImeVisibility(false); 973 dismissSuggestions(); 974 return true; 975 } 976 return false; 977 } 978 979 private boolean onItemSelected(int position) { 980 if (mOnSuggestionListener == null 981 || !mOnSuggestionListener.onSuggestionSelect(position)) { 982 rewriteQueryFromSuggestion(position); 983 return true; 984 } 985 return false; 986 } 987 988 private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() { 989 990 /** 991 * Implements OnItemClickListener 992 */ 993 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 994 if (DBG) Log.d(LOG_TAG, "onItemClick() position " + position); 995 onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null); 996 } 997 }; 998 999 private final OnItemSelectedListener mOnItemSelectedListener = new OnItemSelectedListener() { 1000 1001 /** 1002 * Implements OnItemSelectedListener 1003 */ 1004 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 1005 if (DBG) Log.d(LOG_TAG, "onItemSelected() position " + position); 1006 SearchView.this.onItemSelected(position); 1007 } 1008 1009 /** 1010 * Implements OnItemSelectedListener 1011 */ 1012 public void onNothingSelected(AdapterView<?> parent) { 1013 if (DBG) 1014 Log.d(LOG_TAG, "onNothingSelected()"); 1015 } 1016 }; 1017 1018 /** 1019 * Query rewriting. 1020 */ 1021 private void rewriteQueryFromSuggestion(int position) { 1022 CharSequence oldQuery = mQueryTextView.getText(); 1023 Cursor c = mSuggestionsAdapter.getCursor(); 1024 if (c == null) { 1025 return; 1026 } 1027 if (c.moveToPosition(position)) { 1028 // Get the new query from the suggestion. 1029 CharSequence newQuery = mSuggestionsAdapter.convertToString(c); 1030 if (newQuery != null) { 1031 // The suggestion rewrites the query. 1032 // Update the text field, without getting new suggestions. 1033 setQuery(newQuery); 1034 } else { 1035 // The suggestion does not rewrite the query, restore the user's query. 1036 setQuery(oldQuery); 1037 } 1038 } else { 1039 // We got a bad position, restore the user's query. 1040 setQuery(oldQuery); 1041 } 1042 } 1043 1044 /** 1045 * Launches an intent based on a suggestion. 1046 * 1047 * @param position The index of the suggestion to create the intent from. 1048 * @param actionKey The key code of the action key that was pressed, 1049 * or {@link KeyEvent#KEYCODE_UNKNOWN} if none. 1050 * @param actionMsg The message for the action key that was pressed, 1051 * or <code>null</code> if none. 1052 * @return true if a successful launch, false if could not (e.g. bad position). 1053 */ 1054 private boolean launchSuggestion(int position, int actionKey, String actionMsg) { 1055 Cursor c = mSuggestionsAdapter.getCursor(); 1056 if ((c != null) && c.moveToPosition(position)) { 1057 1058 Intent intent = createIntentFromSuggestion(c, actionKey, actionMsg); 1059 1060 // launch the intent 1061 launchIntent(intent); 1062 1063 return true; 1064 } 1065 return false; 1066 } 1067 1068 /** 1069 * Launches an intent, including any special intent handling. 1070 */ 1071 private void launchIntent(Intent intent) { 1072 if (intent == null) { 1073 return; 1074 } 1075 try { 1076 // If the intent was created from a suggestion, it will always have an explicit 1077 // component here. 1078 getContext().startActivity(intent); 1079 } catch (RuntimeException ex) { 1080 Log.e(LOG_TAG, "Failed launch activity: " + intent, ex); 1081 } 1082 } 1083 1084 /** 1085 * Sets the text in the query box, without updating the suggestions. 1086 */ 1087 private void setQuery(CharSequence query) { 1088 mQueryTextView.setText(query, true); 1089 // Move the cursor to the end 1090 mQueryTextView.setSelection(TextUtils.isEmpty(query) ? 0 : query.length()); 1091 } 1092 1093 private void launchQuerySearch(int actionKey, String actionMsg, String query) { 1094 String action = Intent.ACTION_SEARCH; 1095 Intent intent = createIntent(action, null, null, query, actionKey, actionMsg); 1096 getContext().startActivity(intent); 1097 } 1098 1099 /** 1100 * Constructs an intent from the given information and the search dialog state. 1101 * 1102 * @param action Intent action. 1103 * @param data Intent data, or <code>null</code>. 1104 * @param extraData Data for {@link SearchManager#EXTRA_DATA_KEY} or <code>null</code>. 1105 * @param query Intent query, or <code>null</code>. 1106 * @param actionKey The key code of the action key that was pressed, 1107 * or {@link KeyEvent#KEYCODE_UNKNOWN} if none. 1108 * @param actionMsg The message for the action key that was pressed, 1109 * or <code>null</code> if none. 1110 * @param mode The search mode, one of the acceptable values for 1111 * {@link SearchManager#SEARCH_MODE}, or {@code null}. 1112 * @return The intent. 1113 */ 1114 private Intent createIntent(String action, Uri data, String extraData, String query, 1115 int actionKey, String actionMsg) { 1116 // Now build the Intent 1117 Intent intent = new Intent(action); 1118 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1119 // We need CLEAR_TOP to avoid reusing an old task that has other activities 1120 // on top of the one we want. We don't want to do this in in-app search though, 1121 // as it can be destructive to the activity stack. 1122 if (data != null) { 1123 intent.setData(data); 1124 } 1125 intent.putExtra(SearchManager.USER_QUERY, query); 1126 if (query != null) { 1127 intent.putExtra(SearchManager.QUERY, query); 1128 } 1129 if (extraData != null) { 1130 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData); 1131 } 1132 if (mAppSearchData != null) { 1133 intent.putExtra(SearchManager.APP_DATA, mAppSearchData); 1134 } 1135 if (actionKey != KeyEvent.KEYCODE_UNKNOWN) { 1136 intent.putExtra(SearchManager.ACTION_KEY, actionKey); 1137 intent.putExtra(SearchManager.ACTION_MSG, actionMsg); 1138 } 1139 intent.setComponent(mSearchable.getSearchActivity()); 1140 return intent; 1141 } 1142 1143 /** 1144 * Create and return an Intent that can launch the voice search activity for web search. 1145 */ 1146 private Intent createVoiceWebSearchIntent(Intent baseIntent, SearchableInfo searchable) { 1147 Intent voiceIntent = new Intent(baseIntent); 1148 ComponentName searchActivity = searchable.getSearchActivity(); 1149 voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null 1150 : searchActivity.flattenToShortString()); 1151 return voiceIntent; 1152 } 1153 1154 /** 1155 * Create and return an Intent that can launch the voice search activity, perform a specific 1156 * voice transcription, and forward the results to the searchable activity. 1157 * 1158 * @param baseIntent The voice app search intent to start from 1159 * @return A completely-configured intent ready to send to the voice search activity 1160 */ 1161 private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) { 1162 ComponentName searchActivity = searchable.getSearchActivity(); 1163 1164 // create the necessary intent to set up a search-and-forward operation 1165 // in the voice search system. We have to keep the bundle separate, 1166 // because it becomes immutable once it enters the PendingIntent 1167 Intent queryIntent = new Intent(Intent.ACTION_SEARCH); 1168 queryIntent.setComponent(searchActivity); 1169 PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent, 1170 PendingIntent.FLAG_ONE_SHOT); 1171 1172 // Now set up the bundle that will be inserted into the pending intent 1173 // when it's time to do the search. We always build it here (even if empty) 1174 // because the voice search activity will always need to insert "QUERY" into 1175 // it anyway. 1176 Bundle queryExtras = new Bundle(); 1177 1178 // Now build the intent to launch the voice search. Add all necessary 1179 // extras to launch the voice recognizer, and then all the necessary extras 1180 // to forward the results to the searchable activity 1181 Intent voiceIntent = new Intent(baseIntent); 1182 1183 // Add all of the configuration options supplied by the searchable's metadata 1184 String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM; 1185 String prompt = null; 1186 String language = null; 1187 int maxResults = 1; 1188 1189 Resources resources = getResources(); 1190 if (searchable.getVoiceLanguageModeId() != 0) { 1191 languageModel = resources.getString(searchable.getVoiceLanguageModeId()); 1192 } 1193 if (searchable.getVoicePromptTextId() != 0) { 1194 prompt = resources.getString(searchable.getVoicePromptTextId()); 1195 } 1196 if (searchable.getVoiceLanguageId() != 0) { 1197 language = resources.getString(searchable.getVoiceLanguageId()); 1198 } 1199 if (searchable.getVoiceMaxResults() != 0) { 1200 maxResults = searchable.getVoiceMaxResults(); 1201 } 1202 voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel); 1203 voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt); 1204 voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language); 1205 voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults); 1206 voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null 1207 : searchActivity.flattenToShortString()); 1208 1209 // Add the values that configure forwarding the results 1210 voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending); 1211 voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras); 1212 1213 return voiceIntent; 1214 } 1215 1216 /** 1217 * When a particular suggestion has been selected, perform the various lookups required 1218 * to use the suggestion. This includes checking the cursor for suggestion-specific data, 1219 * and/or falling back to the XML for defaults; It also creates REST style Uri data when 1220 * the suggestion includes a data id. 1221 * 1222 * @param c The suggestions cursor, moved to the row of the user's selection 1223 * @param actionKey The key code of the action key that was pressed, 1224 * or {@link KeyEvent#KEYCODE_UNKNOWN} if none. 1225 * @param actionMsg The message for the action key that was pressed, 1226 * or <code>null</code> if none. 1227 * @return An intent for the suggestion at the cursor's position. 1228 */ 1229 private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) { 1230 try { 1231 // use specific action if supplied, or default action if supplied, or fixed default 1232 String action = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION); 1233 1234 if (action == null) { 1235 action = mSearchable.getSuggestIntentAction(); 1236 } 1237 if (action == null) { 1238 action = Intent.ACTION_SEARCH; 1239 } 1240 1241 // use specific data if supplied, or default data if supplied 1242 String data = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA); 1243 if (data == null) { 1244 data = mSearchable.getSuggestIntentData(); 1245 } 1246 // then, if an ID was provided, append it. 1247 if (data != null) { 1248 String id = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID); 1249 if (id != null) { 1250 data = data + "/" + Uri.encode(id); 1251 } 1252 } 1253 Uri dataUri = (data == null) ? null : Uri.parse(data); 1254 1255 String query = getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY); 1256 String extraData = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA); 1257 1258 return createIntent(action, dataUri, extraData, query, actionKey, actionMsg); 1259 } catch (RuntimeException e ) { 1260 int rowNum; 1261 try { // be really paranoid now 1262 rowNum = c.getPosition(); 1263 } catch (RuntimeException e2 ) { 1264 rowNum = -1; 1265 } 1266 Log.w(LOG_TAG, "Search Suggestions cursor at row " + rowNum + 1267 " returned exception" + e.toString()); 1268 return null; 1269 } 1270 } 1271 1272 static boolean isLandscapeMode(Context context) { 1273 return context.getResources().getConfiguration().orientation 1274 == Configuration.ORIENTATION_LANDSCAPE; 1275 } 1276 1277 /** 1278 * Callback to watch the text field for empty/non-empty 1279 */ 1280 private TextWatcher mTextWatcher = new TextWatcher() { 1281 1282 public void beforeTextChanged(CharSequence s, int start, int before, int after) { } 1283 1284 public void onTextChanged(CharSequence s, int start, 1285 int before, int after) { 1286 SearchView.this.onTextChanged(s); 1287 } 1288 1289 public void afterTextChanged(Editable s) { 1290 } 1291 }; 1292 1293 /** 1294 * Local subclass for AutoCompleteTextView. 1295 * @hide 1296 */ 1297 public static class SearchAutoComplete extends AutoCompleteTextView { 1298 1299 private int mThreshold; 1300 private SearchView mSearchView; 1301 1302 public SearchAutoComplete(Context context) { 1303 super(context); 1304 mThreshold = getThreshold(); 1305 } 1306 1307 public SearchAutoComplete(Context context, AttributeSet attrs) { 1308 super(context, attrs); 1309 mThreshold = getThreshold(); 1310 } 1311 1312 public SearchAutoComplete(Context context, AttributeSet attrs, int defStyle) { 1313 super(context, attrs, defStyle); 1314 mThreshold = getThreshold(); 1315 } 1316 1317 void setSearchView(SearchView searchView) { 1318 mSearchView = searchView; 1319 } 1320 1321 @Override 1322 public void setThreshold(int threshold) { 1323 super.setThreshold(threshold); 1324 mThreshold = threshold; 1325 } 1326 1327 /** 1328 * Returns true if the text field is empty, or contains only whitespace. 1329 */ 1330 private boolean isEmpty() { 1331 return TextUtils.getTrimmedLength(getText()) == 0; 1332 } 1333 1334 /** 1335 * We override this method to avoid replacing the query box text when a 1336 * suggestion is clicked. 1337 */ 1338 @Override 1339 protected void replaceText(CharSequence text) { 1340 } 1341 1342 /** 1343 * We override this method to avoid an extra onItemClick being called on 1344 * the drop-down's OnItemClickListener by 1345 * {@link AutoCompleteTextView#onKeyUp(int, KeyEvent)} when an item is 1346 * clicked with the trackball. 1347 */ 1348 @Override 1349 public void performCompletion() { 1350 } 1351 1352 /** 1353 * We override this method to be sure and show the soft keyboard if 1354 * appropriate when the TextView has focus. 1355 */ 1356 @Override 1357 public void onWindowFocusChanged(boolean hasWindowFocus) { 1358 super.onWindowFocusChanged(hasWindowFocus); 1359 1360 if (hasWindowFocus && mSearchView.hasFocus() && getVisibility() == VISIBLE) { 1361 InputMethodManager inputManager = (InputMethodManager) getContext() 1362 .getSystemService(Context.INPUT_METHOD_SERVICE); 1363 inputManager.showSoftInput(this, 0); 1364 // If in landscape mode, then make sure that 1365 // the ime is in front of the dropdown. 1366 if (isLandscapeMode(getContext())) { 1367 ensureImeVisible(true); 1368 } 1369 } 1370 } 1371 1372 @Override 1373 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 1374 super.onFocusChanged(focused, direction, previouslyFocusedRect); 1375 mSearchView.onTextFocusChanged(); 1376 } 1377 1378 /** 1379 * We override this method so that we can allow a threshold of zero, 1380 * which ACTV does not. 1381 */ 1382 @Override 1383 public boolean enoughToFilter() { 1384 return mThreshold <= 0 || super.enoughToFilter(); 1385 } 1386 } 1387} 1388