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