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