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