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