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