SearchView.java revision 818041428e0aca4943fe5adc0d54dad0d36a75f4
1/* 2 * Copyright (C) 2013 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.support.v7.widget; 18 19import android.app.PendingIntent; 20import android.app.SearchManager; 21import android.app.SearchableInfo; 22import android.content.ActivityNotFoundException; 23import android.content.ComponentName; 24import android.content.Context; 25import android.content.Intent; 26import android.content.pm.PackageManager; 27import android.content.pm.ResolveInfo; 28import android.content.res.Configuration; 29import android.content.res.Resources; 30import android.content.res.TypedArray; 31import android.database.Cursor; 32import android.graphics.Rect; 33import android.graphics.drawable.Drawable; 34import android.net.Uri; 35import android.os.Build; 36import android.os.Bundle; 37import android.speech.RecognizerIntent; 38import android.support.v4.view.KeyEventCompat; 39import android.support.v4.widget.CursorAdapter; 40import android.support.v7.appcompat.R; 41import android.support.v7.internal.view.CollapsibleActionView; 42import android.text.Editable; 43import android.text.InputType; 44import android.text.Spannable; 45import android.text.SpannableStringBuilder; 46import android.text.TextUtils; 47import android.text.TextWatcher; 48import android.text.style.ImageSpan; 49import android.util.AttributeSet; 50import android.util.Log; 51import android.util.TypedValue; 52import android.view.KeyEvent; 53import android.view.LayoutInflater; 54import android.view.View; 55import android.view.ViewTreeObserver; 56import android.view.accessibility.AccessibilityEvent; 57import android.view.accessibility.AccessibilityNodeInfo; 58import android.view.inputmethod.EditorInfo; 59import android.view.inputmethod.InputMethodManager; 60import android.widget.AdapterView; 61import android.widget.AdapterView.OnItemClickListener; 62import android.widget.AdapterView.OnItemSelectedListener; 63import android.widget.AutoCompleteTextView; 64import android.widget.ImageView; 65import android.widget.LinearLayout; 66import android.widget.ListView; 67import android.widget.TextView; 68import android.widget.TextView.OnEditorActionListener; 69 70import java.lang.reflect.InvocationTargetException; 71import java.lang.reflect.Method; 72import java.util.WeakHashMap; 73 74import static android.support.v7.widget.SuggestionsAdapter.getColumnString; 75 76/** 77 * A widget that provides a user interface for the user to enter a search query and submit a request 78 * to a search provider. Shows a list of query suggestions or results, if available, and allows the 79 * user to pick a suggestion or result to launch into. 80 * 81 * <p> 82 * When the SearchView is used in an ActionBar as an action view for a collapsible menu item, it 83 * needs to be set to iconified by default using {@link #setIconifiedByDefault(boolean) 84 * setIconifiedByDefault(true)}. This is the default, so nothing needs to be done. 85 * </p> 86 * <p> 87 * If you want the search field to always be visible, then call setIconifiedByDefault(false). 88 * </p> 89 * 90 * <div class="special reference"> 91 * <h3>Developer Guides</h3> 92 * <p>For information about using {@code SearchView}, read the 93 * <a href="{@docRoot}guide/topics/search/index.html">Search</a> developer guide.</p> 94 * </div> 95 * 96 * @see android.support.v4.view.MenuItemCompat#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW 97 */ 98public class SearchView extends LinearLayout implements CollapsibleActionView { 99 100 private static final boolean DBG = false; 101 private static final String LOG_TAG = "SearchView"; 102 103 /** 104 * Private constant for removing the microphone in the keyboard. 105 */ 106 private static final String IME_OPTION_NO_MICROPHONE = "nm"; 107 108 private OnQueryTextListener mOnQueryChangeListener; 109 private OnCloseListener mOnCloseListener; 110 private View.OnFocusChangeListener mOnQueryTextFocusChangeListener; 111 private OnSuggestionListener mOnSuggestionListener; 112 private OnClickListener mOnSearchClickListener; 113 114 private boolean mIconifiedByDefault; 115 private boolean mIconified; 116 private CursorAdapter mSuggestionsAdapter; 117 private View mSearchButton; 118 private View mSubmitButton; 119 private View mSearchPlate; 120 private View mSubmitArea; 121 private ImageView mCloseButton; 122 private View mSearchEditFrame; 123 private View mVoiceButton; 124 private SearchAutoComplete mQueryTextView; 125 private View mDropDownAnchor; 126 private ImageView mSearchHintIcon; 127 private boolean mSubmitButtonEnabled; 128 private CharSequence mQueryHint; 129 private boolean mQueryRefinement; 130 private boolean mClearingFocus; 131 private int mMaxWidth; 132 private boolean mVoiceButtonEnabled; 133 private CharSequence mOldQueryText; 134 private CharSequence mUserQuery; 135 private boolean mExpandedInActionView; 136 private int mCollapsedImeOptions; 137 138 private SearchableInfo mSearchable; 139 private Bundle mAppSearchData; 140 141 static final AutoCompleteTextViewReflector HIDDEN_METHOD_INVOKER = new AutoCompleteTextViewReflector(); 142 143 /* 144 * SearchView can be set expanded before the IME is ready to be shown during 145 * initial UI setup. The show operation is asynchronous to account for this. 146 */ 147 private Runnable mShowImeRunnable = new Runnable() { 148 public void run() { 149 InputMethodManager imm = (InputMethodManager) 150 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 151 152 if (imm != null) { 153 imm.showSoftInput(SearchView.this, 0); 154 } 155 } 156 }; 157 158 private Runnable mUpdateDrawableStateRunnable = new Runnable() { 159 public void run() { 160 updateFocusedState(); 161 } 162 }; 163 164 private Runnable mReleaseCursorRunnable = new Runnable() { 165 public void run() { 166 if (mSuggestionsAdapter != null && mSuggestionsAdapter instanceof SuggestionsAdapter) { 167 mSuggestionsAdapter.changeCursor(null); 168 } 169 } 170 }; 171 172 // For voice searching 173 private final Intent mVoiceWebSearchIntent; 174 private final Intent mVoiceAppSearchIntent; 175 176 // A weak map of drawables we've gotten from other packages, so we don't load them 177 // more than once. 178 private final WeakHashMap<String, Drawable.ConstantState> mOutsideDrawablesCache = 179 new WeakHashMap<String, Drawable.ConstantState>(); 180 181 /** 182 * Callbacks for changes to the query text. 183 */ 184 public interface OnQueryTextListener { 185 186 /** 187 * Called when the user submits the query. This could be due to a key press on the 188 * keyboard or due to pressing a submit button. 189 * The listener can override the standard behavior by returning true 190 * to indicate that it has handled the submit request. Otherwise return false to 191 * let the SearchView handle the submission by launching any associated intent. 192 * 193 * @param query the query text that is to be submitted 194 * 195 * @return true if the query has been handled by the listener, false to let the 196 * SearchView perform the default action. 197 */ 198 boolean onQueryTextSubmit(String query); 199 200 /** 201 * Called when the query text is changed by the user. 202 * 203 * @param newText the new content of the query text field. 204 * 205 * @return false if the SearchView should perform the default action of showing any 206 * suggestions if available, true if the action was handled by the listener. 207 */ 208 boolean onQueryTextChange(String newText); 209 } 210 211 public interface OnCloseListener { 212 213 /** 214 * The user is attempting to close the SearchView. 215 * 216 * @return true if the listener wants to override the default behavior of clearing the 217 * text field and dismissing it, false otherwise. 218 */ 219 boolean onClose(); 220 } 221 222 /** 223 * Callback interface for selection events on suggestions. These callbacks 224 * are only relevant when a SearchableInfo has been specified by {@link #setSearchableInfo}. 225 */ 226 public interface OnSuggestionListener { 227 228 /** 229 * Called when a suggestion was selected by navigating to it. 230 * @param position the absolute position in the list of suggestions. 231 * 232 * @return true if the listener handles the event and wants to override the default 233 * behavior of possibly rewriting the query based on the selected item, false otherwise. 234 */ 235 boolean onSuggestionSelect(int position); 236 237 /** 238 * Called when a suggestion was clicked. 239 * @param position the absolute position of the clicked item in the list of suggestions. 240 * 241 * @return true if the listener handles the event and wants to override the default 242 * behavior of launching any intent or submitting a search query specified on that item. 243 * Return false otherwise. 244 */ 245 boolean onSuggestionClick(int position); 246 } 247 248 public SearchView(Context context) { 249 this(context, null); 250 } 251 252 public SearchView(Context context, AttributeSet attrs) { 253 super(context, attrs); 254 255 LayoutInflater inflater = (LayoutInflater) context 256 .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 257 inflater.inflate(R.layout.abc_search_view, this, true); 258 259 mSearchButton = findViewById(R.id.search_button); 260 mQueryTextView = (SearchAutoComplete) findViewById(R.id.search_src_text); 261 mQueryTextView.setSearchView(this); 262 263 mSearchEditFrame = findViewById(R.id.search_edit_frame); 264 mSearchPlate = findViewById(R.id.search_plate); 265 mSubmitArea = findViewById(R.id.submit_area); 266 mSubmitButton = findViewById(R.id.search_go_btn); 267 mCloseButton = (ImageView) findViewById(R.id.search_close_btn); 268 mVoiceButton = findViewById(R.id.search_voice_btn); 269 mSearchHintIcon = (ImageView) findViewById(R.id.search_mag_icon); 270 271 mSearchButton.setOnClickListener(mOnClickListener); 272 mCloseButton.setOnClickListener(mOnClickListener); 273 mSubmitButton.setOnClickListener(mOnClickListener); 274 mVoiceButton.setOnClickListener(mOnClickListener); 275 mQueryTextView.setOnClickListener(mOnClickListener); 276 277 mQueryTextView.addTextChangedListener(mTextWatcher); 278 mQueryTextView.setOnEditorActionListener(mOnEditorActionListener); 279 mQueryTextView.setOnItemClickListener(mOnItemClickListener); 280 mQueryTextView.setOnItemSelectedListener(mOnItemSelectedListener); 281 mQueryTextView.setOnKeyListener(mTextKeyListener); 282 // Inform any listener of focus changes 283 mQueryTextView.setOnFocusChangeListener(new OnFocusChangeListener() { 284 285 public void onFocusChange(View v, boolean hasFocus) { 286 if (mOnQueryTextFocusChangeListener != null) { 287 mOnQueryTextFocusChangeListener.onFocusChange(SearchView.this, hasFocus); 288 } 289 } 290 }); 291 292 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SearchView, 0, 0); 293 setIconifiedByDefault(a.getBoolean(R.styleable.SearchView_iconifiedByDefault, true)); 294 int maxWidth = a.getDimensionPixelSize(R.styleable.SearchView_android_maxWidth, -1); 295 if (maxWidth != -1) { 296 setMaxWidth(maxWidth); 297 } 298 CharSequence queryHint = a.getText(R.styleable.SearchView_queryHint); 299 if (!TextUtils.isEmpty(queryHint)) { 300 setQueryHint(queryHint); 301 } 302 int imeOptions = a.getInt(R.styleable.SearchView_android_imeOptions, -1); 303 if (imeOptions != -1) { 304 setImeOptions(imeOptions); 305 } 306 int inputType = a.getInt(R.styleable.SearchView_android_inputType, -1); 307 if (inputType != -1) { 308 setInputType(inputType); 309 } 310 311 a.recycle(); 312 313 boolean focusable = true; 314 315 a = context.obtainStyledAttributes(attrs, R.styleable.View, 0, 0); 316 focusable = a.getBoolean(R.styleable.View_android_focusable, focusable); 317 a.recycle(); 318 setFocusable(focusable); 319 320 // Save voice intent for later queries/launching 321 mVoiceWebSearchIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); 322 mVoiceWebSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 323 mVoiceWebSearchIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 324 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH); 325 326 mVoiceAppSearchIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 327 mVoiceAppSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 328 329 mDropDownAnchor = findViewById(mQueryTextView.getDropDownAnchor()); 330 if (mDropDownAnchor != null) { 331 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 332 addOnLayoutChangeListenerToDropDownAnchorSDK11(); 333 } else { 334 addOnLayoutChangeListenerToDropDownAnchorBase(); 335 } 336 } 337 338 updateViewsVisibility(mIconifiedByDefault); 339 updateQueryHint(); 340 } 341 342 private void addOnLayoutChangeListenerToDropDownAnchorSDK11() { 343 mDropDownAnchor.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { 344 @Override 345 public void onLayoutChange(View v, int left, int top, int right, int bottom, 346 int oldLeft, int oldTop, int oldRight, int oldBottom) { 347 adjustDropDownSizeAndPosition(); 348 } 349 }); 350 } 351 352 private void addOnLayoutChangeListenerToDropDownAnchorBase() { 353 mDropDownAnchor.getViewTreeObserver() 354 .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 355 @Override 356 public void onGlobalLayout() { 357 adjustDropDownSizeAndPosition(); 358 } 359 }); 360 } 361 362 /** 363 * Sets the SearchableInfo for this SearchView. Properties in the SearchableInfo are used 364 * to display labels, hints, suggestions, create intents for launching search results screens 365 * and controlling other affordances such as a voice button. 366 * 367 * @param searchable a SearchableInfo can be retrieved from the SearchManager, for a specific 368 * activity or a global search provider. 369 */ 370 public void setSearchableInfo(SearchableInfo searchable) { 371 mSearchable = searchable; 372 if (mSearchable != null) { 373 updateSearchAutoComplete(); 374 updateQueryHint(); 375 } 376 // Cache the voice search capability 377 mVoiceButtonEnabled = hasVoiceSearch(); 378 379 if (mVoiceButtonEnabled) { 380 // Disable the microphone on the keyboard, as a mic is displayed near the text box 381 // TODO: use imeOptions to disable voice input when the new API will be available 382 mQueryTextView.setPrivateImeOptions(IME_OPTION_NO_MICROPHONE); 383 } 384 updateViewsVisibility(isIconified()); 385 } 386 387 /** 388 * Sets the APP_DATA for legacy SearchDialog use. 389 * @param appSearchData bundle provided by the app when launching the search dialog 390 * @hide 391 */ 392 public void setAppSearchData(Bundle appSearchData) { 393 mAppSearchData = appSearchData; 394 } 395 396 /** 397 * Sets the IME options on the query text field. 398 * 399 * @see TextView#setImeOptions(int) 400 * @param imeOptions the options to set on the query text field 401 * 402 * @attr ref android.R.styleable#SearchView_imeOptions 403 */ 404 public void setImeOptions(int imeOptions) { 405 mQueryTextView.setImeOptions(imeOptions); 406 } 407 408 /** 409 * Returns the IME options set on the query text field. 410 * @return the ime options 411 * @see TextView#setImeOptions(int) 412 * 413 * @attr ref android.R.styleable#SearchView_imeOptions 414 */ 415 public int getImeOptions() { 416 return mQueryTextView.getImeOptions(); 417 } 418 419 /** 420 * Sets the input type on the query text field. 421 * 422 * @see TextView#setInputType(int) 423 * @param inputType the input type to set on the query text field 424 * 425 * @attr ref android.R.styleable#SearchView_inputType 426 */ 427 public void setInputType(int inputType) { 428 mQueryTextView.setInputType(inputType); 429 } 430 431 /** 432 * Returns the input type set on the query text field. 433 * @return the input type 434 * 435 * @attr ref android.R.styleable#SearchView_inputType 436 */ 437 public int getInputType() { 438 return mQueryTextView.getInputType(); 439 } 440 441 /** @hide */ 442 @Override 443 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 444 // Don't accept focus if in the middle of clearing focus 445 if (mClearingFocus) return false; 446 // Check if SearchView is focusable. 447 if (!isFocusable()) return false; 448 // If it is not iconified, then give the focus to the text field 449 if (!isIconified()) { 450 boolean result = mQueryTextView.requestFocus(direction, previouslyFocusedRect); 451 if (result) { 452 updateViewsVisibility(false); 453 } 454 return result; 455 } else { 456 return super.requestFocus(direction, previouslyFocusedRect); 457 } 458 } 459 460 /** @hide */ 461 @Override 462 public void clearFocus() { 463 mClearingFocus = true; 464 setImeVisibility(false); 465 super.clearFocus(); 466 mQueryTextView.clearFocus(); 467 mClearingFocus = false; 468 } 469 470 /** 471 * Sets a listener for user actions within the SearchView. 472 * 473 * @param listener the listener object that receives callbacks when the user performs 474 * actions in the SearchView such as clicking on buttons or typing a query. 475 */ 476 public void setOnQueryTextListener(OnQueryTextListener listener) { 477 mOnQueryChangeListener = listener; 478 } 479 480 /** 481 * Sets a listener to inform when the user closes the SearchView. 482 * 483 * @param listener the listener to call when the user closes the SearchView. 484 */ 485 public void setOnCloseListener(OnCloseListener listener) { 486 mOnCloseListener = listener; 487 } 488 489 /** 490 * Sets a listener to inform when the focus of the query text field changes. 491 * 492 * @param listener the listener to inform of focus changes. 493 */ 494 public void setOnQueryTextFocusChangeListener(OnFocusChangeListener listener) { 495 mOnQueryTextFocusChangeListener = listener; 496 } 497 498 /** 499 * Sets a listener to inform when a suggestion is focused or clicked. 500 * 501 * @param listener the listener to inform of suggestion selection events. 502 */ 503 public void setOnSuggestionListener(OnSuggestionListener listener) { 504 mOnSuggestionListener = listener; 505 } 506 507 /** 508 * Sets a listener to inform when the search button is pressed. This is only 509 * relevant when the text field is not visible by default. Calling {@link #setIconified 510 * setIconified(false)} can also cause this listener to be informed. 511 * 512 * @param listener the listener to inform when the search button is clicked or 513 * the text field is programmatically de-iconified. 514 */ 515 public void setOnSearchClickListener(OnClickListener listener) { 516 mOnSearchClickListener = listener; 517 } 518 519 /** 520 * Returns the query string currently in the text field. 521 * 522 * @return the query string 523 */ 524 public CharSequence getQuery() { 525 return mQueryTextView.getText(); 526 } 527 528 /** 529 * Sets a query string in the text field and optionally submits the query as well. 530 * 531 * @param query the query string. This replaces any query text already present in the 532 * text field. 533 * @param submit whether to submit the query right now or only update the contents of 534 * text field. 535 */ 536 public void setQuery(CharSequence query, boolean submit) { 537 mQueryTextView.setText(query); 538 if (query != null) { 539 mQueryTextView.setSelection(mQueryTextView.length()); 540 mUserQuery = query; 541 } 542 543 // If the query is not empty and submit is requested, submit the query 544 if (submit && !TextUtils.isEmpty(query)) { 545 onSubmitQuery(); 546 } 547 } 548 549 /** 550 * Sets the hint text to display in the query text field. This overrides any hint specified 551 * in the SearchableInfo. 552 * 553 * @param hint the hint text to display 554 * 555 * @attr ref android.R.styleable#SearchView_queryHint 556 */ 557 public void setQueryHint(CharSequence hint) { 558 mQueryHint = hint; 559 updateQueryHint(); 560 } 561 562 /** 563 * Gets the hint text to display in the query text field. 564 * @return the query hint text, if specified, null otherwise. 565 * 566 * @attr ref android.R.styleable#SearchView_queryHint 567 */ 568 public CharSequence getQueryHint() { 569 if (mQueryHint != null) { 570 return mQueryHint; 571 } else if (mSearchable != null) { 572 CharSequence hint = null; 573 int hintId = mSearchable.getHintId(); 574 if (hintId != 0) { 575 hint = getContext().getString(hintId); 576 } 577 return hint; 578 } 579 return null; 580 } 581 582 /** 583 * Sets the default or resting state of the search field. If true, a single search icon is 584 * shown by default and expands to show the text field and other buttons when pressed. Also, 585 * if the default state is iconified, then it collapses to that state when the close button 586 * is pressed. Changes to this property will take effect immediately. 587 * 588 * <p>The default value is true.</p> 589 * 590 * @param iconified whether the search field should be iconified by default 591 * 592 * @attr ref android.R.styleable#SearchView_iconifiedByDefault 593 */ 594 public void setIconifiedByDefault(boolean iconified) { 595 if (mIconifiedByDefault == iconified) return; 596 mIconifiedByDefault = iconified; 597 updateViewsVisibility(iconified); 598 updateQueryHint(); 599 } 600 601 /** 602 * Returns the default iconified state of the search field. 603 * @return 604 * 605 * @attr ref android.R.styleable#SearchView_iconifiedByDefault 606 */ 607 public boolean isIconfiedByDefault() { 608 return mIconifiedByDefault; 609 } 610 611 /** 612 * Iconifies or expands the SearchView. Any query text is cleared when iconified. This is 613 * a temporary state and does not override the default iconified state set by 614 * {@link #setIconifiedByDefault(boolean)}. If the default state is iconified, then 615 * a false here will only be valid until the user closes the field. And if the default 616 * state is expanded, then a true here will only clear the text field and not close it. 617 * 618 * @param iconify a true value will collapse the SearchView to an icon, while a false will 619 * expand it. 620 */ 621 public void setIconified(boolean iconify) { 622 if (iconify) { 623 onCloseClicked(); 624 } else { 625 onSearchClicked(); 626 } 627 } 628 629 /** 630 * Returns the current iconified state of the SearchView. 631 * 632 * @return true if the SearchView is currently iconified, false if the search field is 633 * fully visible. 634 */ 635 public boolean isIconified() { 636 return mIconified; 637 } 638 639 /** 640 * Enables showing a submit button when the query is non-empty. In cases where the SearchView 641 * is being used to filter the contents of the current activity and doesn't launch a separate 642 * results activity, then the submit button should be disabled. 643 * 644 * @param enabled true to show a submit button for submitting queries, false if a submit 645 * button is not required. 646 */ 647 public void setSubmitButtonEnabled(boolean enabled) { 648 mSubmitButtonEnabled = enabled; 649 updateViewsVisibility(isIconified()); 650 } 651 652 /** 653 * Returns whether the submit button is enabled when necessary or never displayed. 654 * 655 * @return whether the submit button is enabled automatically when necessary 656 */ 657 public boolean isSubmitButtonEnabled() { 658 return mSubmitButtonEnabled; 659 } 660 661 /** 662 * Specifies if a query refinement button should be displayed alongside each suggestion 663 * or if it should depend on the flags set in the individual items retrieved from the 664 * suggestions provider. Clicking on the query refinement button will replace the text 665 * in the query text field with the text from the suggestion. This flag only takes effect 666 * if a SearchableInfo has been specified with {@link #setSearchableInfo(SearchableInfo)} 667 * and not when using a custom adapter. 668 * 669 * @param enable true if all items should have a query refinement button, false if only 670 * those items that have a query refinement flag set should have the button. 671 * 672 * @see SearchManager#SUGGEST_COLUMN_FLAGS 673 * @see SearchManager#FLAG_QUERY_REFINEMENT 674 */ 675 public void setQueryRefinementEnabled(boolean enable) { 676 mQueryRefinement = enable; 677 if (mSuggestionsAdapter instanceof SuggestionsAdapter) { 678 ((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement( 679 enable ? SuggestionsAdapter.REFINE_ALL : SuggestionsAdapter.REFINE_BY_ENTRY); 680 } 681 } 682 683 /** 684 * Returns whether query refinement is enabled for all items or only specific ones. 685 * @return true if enabled for all items, false otherwise. 686 */ 687 public boolean isQueryRefinementEnabled() { 688 return mQueryRefinement; 689 } 690 691 /** 692 * You can set a custom adapter if you wish. Otherwise the default adapter is used to 693 * display the suggestions from the suggestions provider associated with the SearchableInfo. 694 * 695 * @see #setSearchableInfo(SearchableInfo) 696 */ 697 public void setSuggestionsAdapter(CursorAdapter adapter) { 698 mSuggestionsAdapter = adapter; 699 700 mQueryTextView.setAdapter(mSuggestionsAdapter); 701 } 702 703 /** 704 * Returns the adapter used for suggestions, if any. 705 * @return the suggestions adapter 706 */ 707 public CursorAdapter getSuggestionsAdapter() { 708 return mSuggestionsAdapter; 709 } 710 711 /** 712 * Makes the view at most this many pixels wide 713 * 714 * @attr ref android.R.styleable#SearchView_maxWidth 715 */ 716 public void setMaxWidth(int maxpixels) { 717 mMaxWidth = maxpixels; 718 719 requestLayout(); 720 } 721 722 /** 723 * Gets the specified maximum width in pixels, if set. Returns zero if 724 * no maximum width was specified. 725 * @return the maximum width of the view 726 * 727 * @attr ref android.R.styleable#SearchView_maxWidth 728 */ 729 public int getMaxWidth() { 730 return mMaxWidth; 731 } 732 733 @Override 734 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 735 // Let the standard measurements take effect in iconified state. 736 if (isIconified()) { 737 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 738 return; 739 } 740 741 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 742 int width = MeasureSpec.getSize(widthMeasureSpec); 743 744 switch (widthMode) { 745 case MeasureSpec.AT_MOST: 746 // If there is an upper limit, don't exceed maximum width (explicit or implicit) 747 if (mMaxWidth > 0) { 748 width = Math.min(mMaxWidth, width); 749 } else { 750 width = Math.min(getPreferredWidth(), width); 751 } 752 break; 753 case MeasureSpec.EXACTLY: 754 // If an exact width is specified, still don't exceed any specified maximum width 755 if (mMaxWidth > 0) { 756 width = Math.min(mMaxWidth, width); 757 } 758 break; 759 case MeasureSpec.UNSPECIFIED: 760 // Use maximum width, if specified, else preferred width 761 width = mMaxWidth > 0 ? mMaxWidth : getPreferredWidth(); 762 break; 763 } 764 widthMode = MeasureSpec.EXACTLY; 765 super.onMeasure(MeasureSpec.makeMeasureSpec(width, widthMode), heightMeasureSpec); 766 } 767 768 private int getPreferredWidth() { 769 return getContext().getResources() 770 .getDimensionPixelSize(R.dimen.search_view_preferred_width); 771 } 772 773 private void updateViewsVisibility(final boolean collapsed) { 774 mIconified = collapsed; 775 // Visibility of views that are visible when collapsed 776 final int visCollapsed = collapsed ? VISIBLE : GONE; 777 // Is there text in the query 778 final boolean hasText = !TextUtils.isEmpty(mQueryTextView.getText()); 779 780 mSearchButton.setVisibility(visCollapsed); 781 updateSubmitButton(hasText); 782 mSearchEditFrame.setVisibility(collapsed ? GONE : VISIBLE); 783 mSearchHintIcon.setVisibility(mIconifiedByDefault ? GONE : VISIBLE); 784 updateCloseButton(); 785 updateVoiceButton(!hasText); 786 updateSubmitArea(); 787 } 788 789 private boolean hasVoiceSearch() { 790 if (mSearchable != null && mSearchable.getVoiceSearchEnabled()) { 791 Intent testIntent = null; 792 if (mSearchable.getVoiceSearchLaunchWebSearch()) { 793 testIntent = mVoiceWebSearchIntent; 794 } else if (mSearchable.getVoiceSearchLaunchRecognizer()) { 795 testIntent = mVoiceAppSearchIntent; 796 } 797 if (testIntent != null) { 798 ResolveInfo ri = getContext().getPackageManager().resolveActivity(testIntent, 799 PackageManager.MATCH_DEFAULT_ONLY); 800 return ri != null; 801 } 802 } 803 return false; 804 } 805 806 private boolean isSubmitAreaEnabled() { 807 return (mSubmitButtonEnabled || mVoiceButtonEnabled) && !isIconified(); 808 } 809 810 private void updateSubmitButton(boolean hasText) { 811 int visibility = GONE; 812 if (mSubmitButtonEnabled && isSubmitAreaEnabled() && hasFocus() 813 && (hasText || !mVoiceButtonEnabled)) { 814 visibility = VISIBLE; 815 } 816 mSubmitButton.setVisibility(visibility); 817 } 818 819 private void updateSubmitArea() { 820 int visibility = GONE; 821 if (isSubmitAreaEnabled() 822 && (mSubmitButton.getVisibility() == VISIBLE 823 || mVoiceButton.getVisibility() == VISIBLE)) { 824 visibility = VISIBLE; 825 } 826 mSubmitArea.setVisibility(visibility); 827 } 828 829 private void updateCloseButton() { 830 final boolean hasText = !TextUtils.isEmpty(mQueryTextView.getText()); 831 // Should we show the close button? It is not shown if there's no focus, 832 // field is not iconified by default and there is no text in it. 833 final boolean showClose = hasText || (mIconifiedByDefault && !mExpandedInActionView); 834 mCloseButton.setVisibility(showClose ? VISIBLE : GONE); 835 mCloseButton.getDrawable().setState(hasText ? ENABLED_STATE_SET : EMPTY_STATE_SET); 836 } 837 838 private void postUpdateFocusedState() { 839 post(mUpdateDrawableStateRunnable); 840 } 841 842 private void updateFocusedState() { 843 boolean focused = mQueryTextView.hasFocus(); 844 mSearchPlate.getBackground().setState(focused ? FOCUSED_STATE_SET : EMPTY_STATE_SET); 845 mSubmitArea.getBackground().setState(focused ? FOCUSED_STATE_SET : EMPTY_STATE_SET); 846 invalidate(); 847 } 848 849 @Override 850 protected void onDetachedFromWindow() { 851 removeCallbacks(mUpdateDrawableStateRunnable); 852 post(mReleaseCursorRunnable); 853 super.onDetachedFromWindow(); 854 } 855 856 private void setImeVisibility(final boolean visible) { 857 if (visible) { 858 post(mShowImeRunnable); 859 } else { 860 removeCallbacks(mShowImeRunnable); 861 InputMethodManager imm = (InputMethodManager) 862 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 863 864 if (imm != null) { 865 imm.hideSoftInputFromWindow(getWindowToken(), 0); 866 } 867 } 868 } 869 870 /** 871 * Called by the SuggestionsAdapter 872 * @hide 873 */ 874 /* package */void onQueryRefine(CharSequence queryText) { 875 setQuery(queryText); 876 } 877 878 private final OnClickListener mOnClickListener = new OnClickListener() { 879 880 public void onClick(View v) { 881 if (v == mSearchButton) { 882 onSearchClicked(); 883 } else if (v == mCloseButton) { 884 onCloseClicked(); 885 } else if (v == mSubmitButton) { 886 onSubmitQuery(); 887 } else if (v == mVoiceButton) { 888 onVoiceClicked(); 889 } else if (v == mQueryTextView) { 890 forceSuggestionQuery(); 891 } 892 } 893 }; 894 895 /** 896 * Handles the key down event for dealing with action keys. 897 * 898 * @param keyCode This is the keycode of the typed key, and is the same value as 899 * found in the KeyEvent parameter. 900 * @param event The complete event record for the typed key 901 * 902 * @return true if the event was handled here, or false if not. 903 */ 904 @Override 905 public boolean onKeyDown(int keyCode, KeyEvent event) { 906 if (mSearchable == null) { 907 return false; 908 } 909 910 return super.onKeyDown(keyCode, event); 911 } 912 913 /** 914 * React to the user typing "enter" or other hardwired keys while typing in 915 * the search box. This handles these special keys while the edit box has 916 * focus. 917 */ 918 View.OnKeyListener mTextKeyListener = new View.OnKeyListener() { 919 public boolean onKey(View v, int keyCode, KeyEvent event) { 920 // guard against possible race conditions 921 if (mSearchable == null) { 922 return false; 923 } 924 925 if (DBG) { 926 Log.d(LOG_TAG, "mTextListener.onKey(" + keyCode + "," + event + "), selection: " 927 + mQueryTextView.getListSelection()); 928 } 929 930 // If a suggestion is selected, handle enter, search key, and action keys 931 // as presses on the selected suggestion 932 if (mQueryTextView.isPopupShowing() 933 && mQueryTextView.getListSelection() != ListView.INVALID_POSITION) { 934 return onSuggestionsKey(v, keyCode, event); 935 } 936 937 // If there is text in the query box, handle enter, and action keys 938 // The search key is handled by the dialog's onKeyDown(). 939 if (!mQueryTextView.isEmpty() && KeyEventCompat.hasNoModifiers(event)) { 940 if (event.getAction() == KeyEvent.ACTION_UP) { 941 if (keyCode == KeyEvent.KEYCODE_ENTER) { 942 v.cancelLongPress(); 943 944 // Launch as a regular search. 945 launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, mQueryTextView.getText() 946 .toString()); 947 return true; 948 } 949 } 950 } 951 return false; 952 } 953 }; 954 955 /** 956 * React to the user typing while in the suggestions list. First, check for 957 * action keys. If not handled, try refocusing regular characters into the 958 * EditText. 959 */ 960 private boolean onSuggestionsKey(View v, int keyCode, KeyEvent event) { 961 // guard against possible race conditions (late arrival after dismiss) 962 if (mSearchable == null) { 963 return false; 964 } 965 if (mSuggestionsAdapter == null) { 966 return false; 967 } 968 if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEventCompat.hasNoModifiers(event)) { 969 // First, check for enter or search (both of which we'll treat as a 970 // "click") 971 if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH 972 || keyCode == KeyEvent.KEYCODE_TAB) { 973 int position = mQueryTextView.getListSelection(); 974 return onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null); 975 } 976 977 // Next, check for left/right moves, which we use to "return" the 978 // user to the edit view 979 if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { 980 // give "focus" to text editor, with cursor at the beginning if 981 // left key, at end if right key 982 int selPoint = (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) ? 0 : mQueryTextView 983 .length(); 984 mQueryTextView.setSelection(selPoint); 985 mQueryTextView.setListSelection(0); 986 mQueryTextView.clearListSelection(); 987 HIDDEN_METHOD_INVOKER.ensureImeVisible(mQueryTextView, true); 988 989 return true; 990 } 991 992 // Next, check for an "up and out" move 993 if (keyCode == KeyEvent.KEYCODE_DPAD_UP && 0 == mQueryTextView.getListSelection()) { 994 // TODO: restoreUserQuery(); 995 // let ACTV complete the move 996 return false; 997 } 998 } 999 return false; 1000 } 1001 1002 private int getSearchIconId() { 1003 TypedValue outValue = new TypedValue(); 1004 getContext().getTheme().resolveAttribute(R.attr.searchViewSearchIcon, outValue, true); 1005 return outValue.resourceId; 1006 } 1007 1008 private CharSequence getDecoratedHint(CharSequence hintText) { 1009 // If the field is always expanded, then don't add the search icon to the hint 1010 if (!mIconifiedByDefault) return hintText; 1011 1012 SpannableStringBuilder ssb = new SpannableStringBuilder(" "); // for the icon 1013 ssb.append(hintText); 1014 Drawable searchIcon = getContext().getResources().getDrawable(getSearchIconId()); 1015 int textSize = (int) (mQueryTextView.getTextSize() * 1.25); 1016 searchIcon.setBounds(0, 0, textSize, textSize); 1017 ssb.setSpan(new ImageSpan(searchIcon), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 1018 return ssb; 1019 } 1020 1021 private void updateQueryHint() { 1022 if (mQueryHint != null) { 1023 mQueryTextView.setHint(getDecoratedHint(mQueryHint)); 1024 } else if (mSearchable != null) { 1025 CharSequence hint = null; 1026 int hintId = mSearchable.getHintId(); 1027 if (hintId != 0) { 1028 hint = getContext().getString(hintId); 1029 } 1030 if (hint != null) { 1031 mQueryTextView.setHint(getDecoratedHint(hint)); 1032 } 1033 } else { 1034 mQueryTextView.setHint(getDecoratedHint("")); 1035 } 1036 } 1037 1038 /** 1039 * Updates the auto-complete text view. 1040 */ 1041 private void updateSearchAutoComplete() { 1042 mQueryTextView.setThreshold(mSearchable.getSuggestThreshold()); 1043 mQueryTextView.setImeOptions(mSearchable.getImeOptions()); 1044 int inputType = mSearchable.getInputType(); 1045 // We only touch this if the input type is set up for text (which it almost certainly 1046 // should be, in the case of search!) 1047 if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) { 1048 // The existence of a suggestions authority is the proxy for "suggestions 1049 // are available here" 1050 inputType &= ~InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE; 1051 if (mSearchable.getSuggestAuthority() != null) { 1052 inputType |= InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE; 1053 // TYPE_TEXT_FLAG_AUTO_COMPLETE means that the text editor is performing 1054 // auto-completion based on its own semantics, which it will present to the user 1055 // as they type. This generally means that the input method should not show its 1056 // own candidates, and the spell checker should not be in action. The text editor 1057 // supplies its candidates by calling InputMethodManager.displayCompletions(), 1058 // which in turn will call InputMethodSession.displayCompletions(). 1059 inputType |= InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; 1060 } 1061 } 1062 mQueryTextView.setInputType(inputType); 1063 if (mSuggestionsAdapter != null) { 1064 mSuggestionsAdapter.changeCursor(null); 1065 } 1066 // attach the suggestions adapter, if suggestions are available 1067 // The existence of a suggestions authority is the proxy for "suggestions available here" 1068 if (mSearchable.getSuggestAuthority() != null) { 1069 mSuggestionsAdapter = new SuggestionsAdapter(getContext(), 1070 this, mSearchable, mOutsideDrawablesCache); 1071 mQueryTextView.setAdapter(mSuggestionsAdapter); 1072 ((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement( 1073 mQueryRefinement ? SuggestionsAdapter.REFINE_ALL 1074 : SuggestionsAdapter.REFINE_BY_ENTRY); 1075 } 1076 } 1077 1078 /** 1079 * Update the visibility of the voice button. There are actually two voice search modes, 1080 * either of which will activate the button. 1081 * @param empty whether the search query text field is empty. If it is, then the other 1082 * criteria apply to make the voice button visible. 1083 */ 1084 private void updateVoiceButton(boolean empty) { 1085 int visibility = GONE; 1086 if (mVoiceButtonEnabled && !isIconified() && empty) { 1087 visibility = VISIBLE; 1088 mSubmitButton.setVisibility(GONE); 1089 } 1090 mVoiceButton.setVisibility(visibility); 1091 } 1092 1093 private final OnEditorActionListener mOnEditorActionListener = new OnEditorActionListener() { 1094 1095 /** 1096 * Called when the input method default action key is pressed. 1097 */ 1098 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 1099 onSubmitQuery(); 1100 return true; 1101 } 1102 }; 1103 1104 private void onTextChanged(CharSequence newText) { 1105 CharSequence text = mQueryTextView.getText(); 1106 mUserQuery = text; 1107 boolean hasText = !TextUtils.isEmpty(text); 1108 updateSubmitButton(hasText); 1109 updateVoiceButton(!hasText); 1110 updateCloseButton(); 1111 updateSubmitArea(); 1112 if (mOnQueryChangeListener != null && !TextUtils.equals(newText, mOldQueryText)) { 1113 mOnQueryChangeListener.onQueryTextChange(newText.toString()); 1114 } 1115 mOldQueryText = newText.toString(); 1116 } 1117 1118 private void onSubmitQuery() { 1119 CharSequence query = mQueryTextView.getText(); 1120 if (query != null && TextUtils.getTrimmedLength(query) > 0) { 1121 if (mOnQueryChangeListener == null 1122 || !mOnQueryChangeListener.onQueryTextSubmit(query.toString())) { 1123 if (mSearchable != null) { 1124 launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString()); 1125 setImeVisibility(false); 1126 } 1127 dismissSuggestions(); 1128 } 1129 } 1130 } 1131 1132 private void dismissSuggestions() { 1133 mQueryTextView.dismissDropDown(); 1134 } 1135 1136 private void onCloseClicked() { 1137 CharSequence text = mQueryTextView.getText(); 1138 if (TextUtils.isEmpty(text)) { 1139 if (mIconifiedByDefault) { 1140 // If the app doesn't override the close behavior 1141 if (mOnCloseListener == null || !mOnCloseListener.onClose()) { 1142 // hide the keyboard and remove focus 1143 clearFocus(); 1144 // collapse the search field 1145 updateViewsVisibility(true); 1146 } 1147 } 1148 } else { 1149 mQueryTextView.setText(""); 1150 mQueryTextView.requestFocus(); 1151 setImeVisibility(true); 1152 } 1153 1154 } 1155 1156 private void onSearchClicked() { 1157 updateViewsVisibility(false); 1158 mQueryTextView.requestFocus(); 1159 setImeVisibility(true); 1160 if (mOnSearchClickListener != null) { 1161 mOnSearchClickListener.onClick(this); 1162 } 1163 } 1164 1165 private void onVoiceClicked() { 1166 // guard against possible race conditions 1167 if (mSearchable == null) { 1168 return; 1169 } 1170 SearchableInfo searchable = mSearchable; 1171 try { 1172 if (searchable.getVoiceSearchLaunchWebSearch()) { 1173 Intent webSearchIntent = createVoiceWebSearchIntent(mVoiceWebSearchIntent, 1174 searchable); 1175 getContext().startActivity(webSearchIntent); 1176 } else if (searchable.getVoiceSearchLaunchRecognizer()) { 1177 Intent appSearchIntent = createVoiceAppSearchIntent(mVoiceAppSearchIntent, 1178 searchable); 1179 getContext().startActivity(appSearchIntent); 1180 } 1181 } catch (ActivityNotFoundException e) { 1182 // Should not happen, since we check the availability of 1183 // voice search before showing the button. But just in case... 1184 Log.w(LOG_TAG, "Could not find voice search activity"); 1185 } 1186 } 1187 1188 void onTextFocusChanged() { 1189 updateViewsVisibility(isIconified()); 1190 // Delayed update to make sure that the focus has settled down and window focus changes 1191 // don't affect it. A synchronous update was not working. 1192 postUpdateFocusedState(); 1193 if (mQueryTextView.hasFocus()) { 1194 forceSuggestionQuery(); 1195 } 1196 } 1197 1198 @Override 1199 public void onWindowFocusChanged(boolean hasWindowFocus) { 1200 super.onWindowFocusChanged(hasWindowFocus); 1201 1202 postUpdateFocusedState(); 1203 } 1204 1205 /** 1206 * {@inheritDoc} 1207 */ 1208 @Override 1209 public void onActionViewCollapsed() { 1210 clearFocus(); 1211 updateViewsVisibility(true); 1212 mQueryTextView.setImeOptions(mCollapsedImeOptions); 1213 mExpandedInActionView = false; 1214 } 1215 1216 /** 1217 * {@inheritDoc} 1218 */ 1219 @Override 1220 public void onActionViewExpanded() { 1221 if (mExpandedInActionView) return; 1222 1223 mExpandedInActionView = true; 1224 mCollapsedImeOptions = mQueryTextView.getImeOptions(); 1225 mQueryTextView.setImeOptions(mCollapsedImeOptions | EditorInfo.IME_FLAG_NO_FULLSCREEN); 1226 mQueryTextView.setText(""); 1227 setIconified(false); 1228 } 1229 1230 1231 private void adjustDropDownSizeAndPosition() { 1232 if (mDropDownAnchor.getWidth() > 1) { 1233 Resources res = getContext().getResources(); 1234 int anchorPadding = mSearchPlate.getPaddingLeft(); 1235 Rect dropDownPadding = new Rect(); 1236 int iconOffset = mIconifiedByDefault 1237 ? res.getDimensionPixelSize(R.dimen.dropdownitem_icon_width) 1238 + res.getDimensionPixelSize(R.dimen.dropdownitem_text_padding_left) 1239 : 0; 1240 mQueryTextView.getDropDownBackground().getPadding(dropDownPadding); 1241 int offset = anchorPadding - (dropDownPadding.left + iconOffset); 1242 mQueryTextView.setDropDownHorizontalOffset(offset); 1243 final int width = mDropDownAnchor.getWidth() + dropDownPadding.left 1244 + dropDownPadding.right + iconOffset - anchorPadding; 1245 mQueryTextView.setDropDownWidth(width); 1246 } 1247 } 1248 1249 private boolean onItemClicked(int position, int actionKey, String actionMsg) { 1250 if (mOnSuggestionListener == null 1251 || !mOnSuggestionListener.onSuggestionClick(position)) { 1252 launchSuggestion(position, KeyEvent.KEYCODE_UNKNOWN, null); 1253 setImeVisibility(false); 1254 dismissSuggestions(); 1255 return true; 1256 } 1257 return false; 1258 } 1259 1260 private boolean onItemSelected(int position) { 1261 if (mOnSuggestionListener == null 1262 || !mOnSuggestionListener.onSuggestionSelect(position)) { 1263 rewriteQueryFromSuggestion(position); 1264 return true; 1265 } 1266 return false; 1267 } 1268 1269 private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() { 1270 1271 /** 1272 * Implements OnItemClickListener 1273 */ 1274 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1275 if (DBG) Log.d(LOG_TAG, "onItemClick() position " + position); 1276 onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null); 1277 } 1278 }; 1279 1280 private final OnItemSelectedListener mOnItemSelectedListener = new OnItemSelectedListener() { 1281 1282 /** 1283 * Implements OnItemSelectedListener 1284 */ 1285 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 1286 if (DBG) Log.d(LOG_TAG, "onItemSelected() position " + position); 1287 SearchView.this.onItemSelected(position); 1288 } 1289 1290 /** 1291 * Implements OnItemSelectedListener 1292 */ 1293 public void onNothingSelected(AdapterView<?> parent) { 1294 if (DBG) 1295 Log.d(LOG_TAG, "onNothingSelected()"); 1296 } 1297 }; 1298 1299 /** 1300 * Query rewriting. 1301 */ 1302 private void rewriteQueryFromSuggestion(int position) { 1303 CharSequence oldQuery = mQueryTextView.getText(); 1304 Cursor c = mSuggestionsAdapter.getCursor(); 1305 if (c == null) { 1306 return; 1307 } 1308 if (c.moveToPosition(position)) { 1309 // Get the new query from the suggestion. 1310 CharSequence newQuery = mSuggestionsAdapter.convertToString(c); 1311 if (newQuery != null) { 1312 // The suggestion rewrites the query. 1313 // Update the text field, without getting new suggestions. 1314 setQuery(newQuery); 1315 } else { 1316 // The suggestion does not rewrite the query, restore the user's query. 1317 setQuery(oldQuery); 1318 } 1319 } else { 1320 // We got a bad position, restore the user's query. 1321 setQuery(oldQuery); 1322 } 1323 } 1324 1325 /** 1326 * Launches an intent based on a suggestion. 1327 * 1328 * @param position The index of the suggestion to create the intent from. 1329 * @param actionKey The key code of the action key that was pressed, 1330 * or {@link KeyEvent#KEYCODE_UNKNOWN} if none. 1331 * @param actionMsg The message for the action key that was pressed, 1332 * or <code>null</code> if none. 1333 * @return true if a successful launch, false if could not (e.g. bad position). 1334 */ 1335 private boolean launchSuggestion(int position, int actionKey, String actionMsg) { 1336 Cursor c = mSuggestionsAdapter.getCursor(); 1337 if ((c != null) && c.moveToPosition(position)) { 1338 1339 Intent intent = createIntentFromSuggestion(c, actionKey, actionMsg); 1340 1341 // launch the intent 1342 launchIntent(intent); 1343 1344 return true; 1345 } 1346 return false; 1347 } 1348 1349 /** 1350 * Launches an intent, including any special intent handling. 1351 */ 1352 private void launchIntent(Intent intent) { 1353 if (intent == null) { 1354 return; 1355 } 1356 try { 1357 // If the intent was created from a suggestion, it will always have an explicit 1358 // component here. 1359 getContext().startActivity(intent); 1360 } catch (RuntimeException ex) { 1361 Log.e(LOG_TAG, "Failed launch activity: " + intent, ex); 1362 } 1363 } 1364 1365 /** 1366 * Sets the text in the query box, without updating the suggestions. 1367 */ 1368 private void setQuery(CharSequence query) { 1369 mQueryTextView.setText(query); 1370 // Move the cursor to the end 1371 mQueryTextView.setSelection(TextUtils.isEmpty(query) ? 0 : query.length()); 1372 } 1373 1374 private void launchQuerySearch(int actionKey, String actionMsg, String query) { 1375 String action = Intent.ACTION_SEARCH; 1376 Intent intent = createIntent(action, null, null, query, actionKey, actionMsg); 1377 getContext().startActivity(intent); 1378 } 1379 1380 /** 1381 * Constructs an intent from the given information and the search dialog state. 1382 * 1383 * @param action Intent action. 1384 * @param data Intent data, or <code>null</code>. 1385 * @param extraData Data for {@link SearchManager#EXTRA_DATA_KEY} or <code>null</code>. 1386 * @param query Intent query, or <code>null</code>. 1387 * @param actionKey The key code of the action key that was pressed, 1388 * or {@link KeyEvent#KEYCODE_UNKNOWN} if none. 1389 * @param actionMsg The message for the action key that was pressed, 1390 * or <code>null</code> if none. 1391 * @return The intent. 1392 */ 1393 private Intent createIntent(String action, Uri data, String extraData, String query, 1394 int actionKey, String actionMsg) { 1395 // Now build the Intent 1396 Intent intent = new Intent(action); 1397 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1398 // We need CLEAR_TOP to avoid reusing an old task that has other activities 1399 // on top of the one we want. We don't want to do this in in-app search though, 1400 // as it can be destructive to the activity stack. 1401 if (data != null) { 1402 intent.setData(data); 1403 } 1404 intent.putExtra(SearchManager.USER_QUERY, mUserQuery); 1405 if (query != null) { 1406 intent.putExtra(SearchManager.QUERY, query); 1407 } 1408 if (extraData != null) { 1409 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData); 1410 } 1411 if (mAppSearchData != null) { 1412 intent.putExtra(SearchManager.APP_DATA, mAppSearchData); 1413 } 1414 if (actionKey != KeyEvent.KEYCODE_UNKNOWN) { 1415 intent.putExtra(SearchManager.ACTION_KEY, actionKey); 1416 intent.putExtra(SearchManager.ACTION_MSG, actionMsg); 1417 } 1418 intent.setComponent(mSearchable.getSearchActivity()); 1419 return intent; 1420 } 1421 1422 /** 1423 * Create and return an Intent that can launch the voice search activity for web search. 1424 */ 1425 private Intent createVoiceWebSearchIntent(Intent baseIntent, SearchableInfo searchable) { 1426 Intent voiceIntent = new Intent(baseIntent); 1427 ComponentName searchActivity = searchable.getSearchActivity(); 1428 voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null 1429 : searchActivity.flattenToShortString()); 1430 return voiceIntent; 1431 } 1432 1433 /** 1434 * Create and return an Intent that can launch the voice search activity, perform a specific 1435 * voice transcription, and forward the results to the searchable activity. 1436 * 1437 * @param baseIntent The voice app search intent to start from 1438 * @return A completely-configured intent ready to send to the voice search activity 1439 */ 1440 private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) { 1441 ComponentName searchActivity = searchable.getSearchActivity(); 1442 1443 // create the necessary intent to set up a search-and-forward operation 1444 // in the voice search system. We have to keep the bundle separate, 1445 // because it becomes immutable once it enters the PendingIntent 1446 Intent queryIntent = new Intent(Intent.ACTION_SEARCH); 1447 queryIntent.setComponent(searchActivity); 1448 PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent, 1449 PendingIntent.FLAG_ONE_SHOT); 1450 1451 // Now set up the bundle that will be inserted into the pending intent 1452 // when it's time to do the search. We always build it here (even if empty) 1453 // because the voice search activity will always need to insert "QUERY" into 1454 // it anyway. 1455 Bundle queryExtras = new Bundle(); 1456 if (mAppSearchData != null) { 1457 queryExtras.putParcelable(SearchManager.APP_DATA, mAppSearchData); 1458 } 1459 1460 // Now build the intent to launch the voice search. Add all necessary 1461 // extras to launch the voice recognizer, and then all the necessary extras 1462 // to forward the results to the searchable activity 1463 Intent voiceIntent = new Intent(baseIntent); 1464 1465 // Add all of the configuration options supplied by the searchable's metadata 1466 String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM; 1467 String prompt = null; 1468 String language = null; 1469 int maxResults = 1; 1470 1471 Resources resources = getResources(); 1472 if (searchable.getVoiceLanguageModeId() != 0) { 1473 languageModel = resources.getString(searchable.getVoiceLanguageModeId()); 1474 } 1475 if (searchable.getVoicePromptTextId() != 0) { 1476 prompt = resources.getString(searchable.getVoicePromptTextId()); 1477 } 1478 if (searchable.getVoiceLanguageId() != 0) { 1479 language = resources.getString(searchable.getVoiceLanguageId()); 1480 } 1481 if (searchable.getVoiceMaxResults() != 0) { 1482 maxResults = searchable.getVoiceMaxResults(); 1483 } 1484 voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel); 1485 voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt); 1486 voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language); 1487 voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults); 1488 voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null 1489 : searchActivity.flattenToShortString()); 1490 1491 // Add the values that configure forwarding the results 1492 voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending); 1493 voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras); 1494 1495 return voiceIntent; 1496 } 1497 1498 /** 1499 * When a particular suggestion has been selected, perform the various lookups required 1500 * to use the suggestion. This includes checking the cursor for suggestion-specific data, 1501 * and/or falling back to the XML for defaults; It also creates REST style Uri data when 1502 * the suggestion includes a data id. 1503 * 1504 * @param c The suggestions cursor, moved to the row of the user's selection 1505 * @param actionKey The key code of the action key that was pressed, 1506 * or {@link KeyEvent#KEYCODE_UNKNOWN} if none. 1507 * @param actionMsg The message for the action key that was pressed, 1508 * or <code>null</code> if none. 1509 * @return An intent for the suggestion at the cursor's position. 1510 */ 1511 private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) { 1512 try { 1513 // use specific action if supplied, or default action if supplied, or fixed default 1514 String action = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION); 1515 1516 if (action == null) { 1517 action = mSearchable.getSuggestIntentAction(); 1518 } 1519 if (action == null) { 1520 action = Intent.ACTION_SEARCH; 1521 } 1522 1523 // use specific data if supplied, or default data if supplied 1524 String data = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA); 1525 if (data == null) { 1526 data = mSearchable.getSuggestIntentData(); 1527 } 1528 // then, if an ID was provided, append it. 1529 if (data != null) { 1530 String id = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID); 1531 if (id != null) { 1532 data = data + "/" + Uri.encode(id); 1533 } 1534 } 1535 Uri dataUri = (data == null) ? null : Uri.parse(data); 1536 1537 String query = getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY); 1538 String extraData = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA); 1539 1540 return createIntent(action, dataUri, extraData, query, actionKey, actionMsg); 1541 } catch (RuntimeException e ) { 1542 int rowNum; 1543 try { // be really paranoid now 1544 rowNum = c.getPosition(); 1545 } catch (RuntimeException e2 ) { 1546 rowNum = -1; 1547 } 1548 Log.w(LOG_TAG, "Search suggestions cursor at row " + rowNum + 1549 " returned exception.", e); 1550 return null; 1551 } 1552 } 1553 1554 private void forceSuggestionQuery() { 1555 try { 1556 Method before = AutoCompleteTextView.class.getDeclaredMethod("doBeforeTextChanged"); 1557 Method after = AutoCompleteTextView.class.getDeclaredMethod("doAfterTextChanged"); 1558 before.setAccessible(true); 1559 after.setAccessible(true); 1560 before.invoke(mQueryTextView); 1561 after.invoke(mQueryTextView); 1562 } catch (Exception e) { 1563 // Oh well... 1564 } 1565 1566 HIDDEN_METHOD_INVOKER.doBeforeTextChanged(mQueryTextView); 1567 HIDDEN_METHOD_INVOKER.doAfterTextChanged(mQueryTextView); 1568 } 1569 1570 static boolean isLandscapeMode(Context context) { 1571 return context.getResources().getConfiguration().orientation 1572 == Configuration.ORIENTATION_LANDSCAPE; 1573 } 1574 1575 /** 1576 * Callback to watch the text field for empty/non-empty 1577 */ 1578 private TextWatcher mTextWatcher = new TextWatcher() { 1579 1580 public void beforeTextChanged(CharSequence s, int start, int before, int after) { } 1581 1582 public void onTextChanged(CharSequence s, int start, 1583 int before, int after) { 1584 SearchView.this.onTextChanged(s); 1585 } 1586 1587 public void afterTextChanged(Editable s) { 1588 } 1589 }; 1590 1591 /** 1592 * Local subclass for AutoCompleteTextView. 1593 * @hide 1594 */ 1595 public static class SearchAutoComplete extends AutoCompleteTextView { 1596 1597 private int mThreshold; 1598 private SearchView mSearchView; 1599 1600 public SearchAutoComplete(Context context) { 1601 super(context); 1602 mThreshold = getThreshold(); 1603 } 1604 1605 public SearchAutoComplete(Context context, AttributeSet attrs) { 1606 super(context, attrs); 1607 mThreshold = getThreshold(); 1608 } 1609 1610 public SearchAutoComplete(Context context, AttributeSet attrs, int defStyle) { 1611 super(context, attrs, defStyle); 1612 mThreshold = getThreshold(); 1613 } 1614 1615 void setSearchView(SearchView searchView) { 1616 mSearchView = searchView; 1617 } 1618 1619 @Override 1620 public void setThreshold(int threshold) { 1621 super.setThreshold(threshold); 1622 mThreshold = threshold; 1623 } 1624 1625 /** 1626 * Returns true if the text field is empty, or contains only whitespace. 1627 */ 1628 private boolean isEmpty() { 1629 return TextUtils.getTrimmedLength(getText()) == 0; 1630 } 1631 1632 /** 1633 * We override this method to avoid replacing the query box text when a 1634 * suggestion is clicked. 1635 */ 1636 @Override 1637 protected void replaceText(CharSequence text) { 1638 } 1639 1640 /** 1641 * We override this method to avoid an extra onItemClick being called on 1642 * the drop-down's OnItemClickListener by 1643 * {@link AutoCompleteTextView#onKeyUp(int, KeyEvent)} when an item is 1644 * clicked with the trackball. 1645 */ 1646 @Override 1647 public void performCompletion() { 1648 } 1649 1650 /** 1651 * We override this method to be sure and show the soft keyboard if 1652 * appropriate when the TextView has focus. 1653 */ 1654 @Override 1655 public void onWindowFocusChanged(boolean hasWindowFocus) { 1656 super.onWindowFocusChanged(hasWindowFocus); 1657 1658 if (hasWindowFocus && mSearchView.hasFocus() && getVisibility() == VISIBLE) { 1659 InputMethodManager inputManager = (InputMethodManager) getContext() 1660 .getSystemService(Context.INPUT_METHOD_SERVICE); 1661 inputManager.showSoftInput(this, 0); 1662 // If in landscape mode, then make sure that 1663 // the ime is in front of the dropdown. 1664 if (isLandscapeMode(getContext())) { 1665 HIDDEN_METHOD_INVOKER.ensureImeVisible(this, true); 1666 } 1667 } 1668 } 1669 1670 @Override 1671 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 1672 super.onFocusChanged(focused, direction, previouslyFocusedRect); 1673 mSearchView.onTextFocusChanged(); 1674 } 1675 1676 /** 1677 * We override this method so that we can allow a threshold of zero, 1678 * which ACTV does not. 1679 */ 1680 @Override 1681 public boolean enoughToFilter() { 1682 return mThreshold <= 0 || super.enoughToFilter(); 1683 } 1684 1685 @Override 1686 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 1687 if (keyCode == KeyEvent.KEYCODE_BACK) { 1688 // special case for the back key, we do not even try to send it 1689 // to the drop down list but instead, consume it immediately 1690 if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { 1691 KeyEvent.DispatcherState state = getKeyDispatcherState(); 1692 if (state != null) { 1693 state.startTracking(event, this); 1694 } 1695 return true; 1696 } else if (event.getAction() == KeyEvent.ACTION_UP) { 1697 KeyEvent.DispatcherState state = getKeyDispatcherState(); 1698 if (state != null) { 1699 state.handleUpEvent(event); 1700 } 1701 if (event.isTracking() && !event.isCanceled()) { 1702 mSearchView.clearFocus(); 1703 mSearchView.setImeVisibility(false); 1704 return true; 1705 } 1706 } 1707 } 1708 return super.onKeyPreIme(keyCode, event); 1709 } 1710 } 1711 1712 private static class AutoCompleteTextViewReflector { 1713 private Method doBeforeTextChanged, doAfterTextChanged; 1714 private Method ensureImeVisible; 1715 1716 AutoCompleteTextViewReflector() { 1717 try { 1718 doBeforeTextChanged = AutoCompleteTextView.class 1719 .getDeclaredMethod("doBeforeTextChanged"); 1720 doBeforeTextChanged.setAccessible(true); 1721 } catch (NoSuchMethodException e) { 1722 // Ah well. 1723 } 1724 try { 1725 doAfterTextChanged = AutoCompleteTextView.class 1726 .getDeclaredMethod("doAfterTextChanged"); 1727 doAfterTextChanged.setAccessible(true); 1728 } catch (NoSuchMethodException e) { 1729 // Ah well. 1730 } 1731 try { 1732 ensureImeVisible = AutoCompleteTextView.class 1733 .getMethod("ensureImeVisible", Boolean.TYPE); 1734 ensureImeVisible.setAccessible(true); 1735 } catch (NoSuchMethodException e) { 1736 // Ah well. 1737 } 1738 } 1739 1740 void doBeforeTextChanged(AutoCompleteTextView view) { 1741 if (doBeforeTextChanged != null) { 1742 try { 1743 doBeforeTextChanged.invoke(view); 1744 } catch (IllegalAccessException e) { 1745 } catch (InvocationTargetException e) { 1746 } 1747 } 1748 } 1749 1750 void doAfterTextChanged(AutoCompleteTextView view) { 1751 if (doAfterTextChanged != null) { 1752 try { 1753 doAfterTextChanged.invoke(view); 1754 } catch (IllegalAccessException e) { 1755 } catch (InvocationTargetException e) { 1756 } 1757 } 1758 } 1759 1760 void ensureImeVisible(AutoCompleteTextView view, boolean visible) { 1761 if (ensureImeVisible != null) { 1762 try { 1763 ensureImeVisible.invoke(view, visible); 1764 } catch (IllegalAccessException e) { 1765 } catch (InvocationTargetException e) { 1766 } 1767 } 1768 } 1769 } 1770}