SearchView.java revision abdf0d533c292709e51cee2c1213d5e44baca963
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.widget;
18
19import static android.widget.SuggestionsAdapter.getColumnString;
20
21import com.android.internal.R;
22
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.content.res.TypedArray;
35import android.database.Cursor;
36import android.graphics.Rect;
37import android.graphics.drawable.Drawable;
38import android.net.Uri;
39import android.os.Bundle;
40import android.speech.RecognizerIntent;
41import android.text.Editable;
42import android.text.TextUtils;
43import android.text.TextWatcher;
44import android.util.AttributeSet;
45import android.util.Log;
46import android.view.KeyEvent;
47import android.view.LayoutInflater;
48import android.view.View;
49import android.view.inputmethod.InputMethodManager;
50import android.widget.AdapterView.OnItemClickListener;
51import android.widget.AdapterView.OnItemSelectedListener;
52import android.widget.TextView.OnEditorActionListener;
53
54import java.util.WeakHashMap;
55
56/**
57 * A widget that provides a user interface for the user to enter a search query and submit a
58 * request to a search provider. Shows a list of query suggestions or results, if
59 * available, and allows the user to pick a suggestion or result to launch into.
60 *
61 * <p>For more information, see the <a href="{@docRoot}guide/topics/search/index.html">Search</a>
62 * documentation.<p>
63 *
64 * @attr ref android.R.styleable#SearchView_iconifiedByDefault
65 * @attr ref android.R.styleable#SearchView_maxWidth
66 * @attr ref android.R.styleable#SearchView_queryHint
67 */
68public class SearchView extends LinearLayout {
69
70    private static final boolean DBG = false;
71    private static final String LOG_TAG = "SearchView";
72
73    private OnQueryTextListener mOnQueryChangeListener;
74    private OnCloseListener mOnCloseListener;
75    private OnFocusChangeListener mOnQueryTextFocusChangeListener;
76    private OnSuggestionListener mOnSuggestionListener;
77    private OnClickListener mOnSearchClickListener;
78
79    private boolean mIconifiedByDefault;
80    private boolean mIconified;
81    private CursorAdapter mSuggestionsAdapter;
82    private View mSearchButton;
83    private View mSubmitButton;
84    private View mSubmitArea;
85    private ImageView mCloseButton;
86    private View mSearchEditFrame;
87    private View mVoiceButton;
88    private SearchAutoComplete mQueryTextView;
89    private boolean mSubmitButtonEnabled;
90    private CharSequence mQueryHint;
91    private boolean mQueryRefinement;
92    private boolean mClearingFocus;
93    private int mMaxWidth;
94    private boolean mVoiceButtonEnabled;
95
96    private SearchableInfo mSearchable;
97
98    // For voice searching
99    private final Intent mVoiceWebSearchIntent;
100    private final Intent mVoiceAppSearchIntent;
101
102    // A weak map of drawables we've gotten from other packages, so we don't load them
103    // more than once.
104    private final WeakHashMap<String, Drawable.ConstantState> mOutsideDrawablesCache =
105            new WeakHashMap<String, Drawable.ConstantState>();
106
107    /**
108     * Callbacks for changes to the query text.
109     */
110    public interface OnQueryTextListener {
111
112        /**
113         * Called when the user submits the query. This could be due to a key press on the
114         * keyboard or due to pressing a submit button.
115         * The listener can override the standard behavior by returning true
116         * to indicate that it has handled the submit request. Otherwise return false to
117         * let the SearchView handle the submission by launching any associated intent.
118         *
119         * @param query the query text that is to be submitted
120         *
121         * @return true if the query has been handled by the listener, false to let the
122         * SearchView perform the default action.
123         */
124        boolean onQueryTextSubmit(String query);
125
126        /**
127         * Called when the query text is changed by the user.
128         *
129         * @param newText the new content of the query text field.
130         *
131         * @return false if the SearchView should perform the default action of showing any
132         * suggestions if available, true if the action was handled by the listener.
133         */
134        boolean onQueryTextChange(String newText);
135    }
136
137    public interface OnCloseListener {
138
139        /**
140         * The user is attempting to close the SearchView.
141         *
142         * @return true if the listener wants to override the default behavior of clearing the
143         * text field and dismissing it, false otherwise.
144         */
145        boolean onClose();
146    }
147
148    /**
149     * Callback interface for selection events on suggestions. These callbacks
150     * are only relevant when a SearchableInfo has been specified by {@link #setSearchableInfo}.
151     */
152    public interface OnSuggestionListener {
153
154        /**
155         * Called when a suggestion was selected by navigating to it.
156         * @param position the absolute position in the list of suggestions.
157         *
158         * @return true if the listener handles the event and wants to override the default
159         * behavior of possibly rewriting the query based on the selected item, false otherwise.
160         */
161        boolean onSuggestionSelect(int position);
162
163        /**
164         * Called when a suggestion was clicked.
165         * @param position the absolute position of the clicked item in the list of suggestions.
166         *
167         * @return true if the listener handles the event and wants to override the default
168         * behavior of launching any intent or submitting a search query specified on that item.
169         * Return false otherwise.
170         */
171        boolean onSuggestionClick(int position);
172    }
173
174    public SearchView(Context context) {
175        this(context, null);
176    }
177
178    public SearchView(Context context, AttributeSet attrs) {
179        super(context, attrs);
180
181        LayoutInflater inflater = (LayoutInflater) context
182                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
183        inflater.inflate(R.layout.search_view, this, true);
184
185        mSearchButton = findViewById(R.id.search_button);
186        mQueryTextView = (SearchAutoComplete) findViewById(R.id.search_src_text);
187        mQueryTextView.setSearchView(this);
188
189        mSearchEditFrame = findViewById(R.id.search_edit_frame);
190        mSubmitArea = findViewById(R.id.submit_area);
191        mSubmitButton = findViewById(R.id.search_go_btn);
192        mCloseButton = (ImageView) findViewById(R.id.search_close_btn);
193        mVoiceButton = findViewById(R.id.search_voice_btn);
194
195        mSearchButton.setOnClickListener(mOnClickListener);
196        mCloseButton.setOnClickListener(mOnClickListener);
197        mSubmitButton.setOnClickListener(mOnClickListener);
198        mVoiceButton.setOnClickListener(mOnClickListener);
199
200        mQueryTextView.addTextChangedListener(mTextWatcher);
201        mQueryTextView.setOnEditorActionListener(mOnEditorActionListener);
202        mQueryTextView.setOnItemClickListener(mOnItemClickListener);
203        mQueryTextView.setOnItemSelectedListener(mOnItemSelectedListener);
204        mQueryTextView.setOnKeyListener(mTextKeyListener);
205        // Inform any listener of focus changes
206        mQueryTextView.setOnFocusChangeListener(new OnFocusChangeListener() {
207
208            public void onFocusChange(View v, boolean hasFocus) {
209                if (mOnQueryTextFocusChangeListener != null) {
210                    mOnQueryTextFocusChangeListener.onFocusChange(SearchView.this, hasFocus);
211                }
212            }
213        });
214
215        boolean focusable = true;
216
217        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SearchView, 0, 0);
218        setIconifiedByDefault(a.getBoolean(R.styleable.SearchView_iconifiedByDefault, true));
219        int maxWidth = a.getDimensionPixelSize(R.styleable.SearchView_maxWidth, -1);
220        if (maxWidth != -1) {
221            setMaxWidth(maxWidth);
222        }
223        CharSequence queryHint = a.getText(R.styleable.SearchView_queryHint);
224        if (!TextUtils.isEmpty(queryHint)) {
225            setQueryHint(queryHint);
226        }
227        a.recycle();
228
229        a = context.obtainStyledAttributes(attrs, R.styleable.View, 0, 0);
230        focusable = a.getBoolean(R.styleable.View_focusable, focusable);
231        a.recycle();
232        setFocusable(focusable);
233
234        // Save voice intent for later queries/launching
235        mVoiceWebSearchIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
236        mVoiceWebSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
237        mVoiceWebSearchIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
238                RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
239
240        mVoiceAppSearchIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
241        mVoiceAppSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
242
243        updateViewsVisibility(mIconifiedByDefault);
244    }
245
246    /**
247     * Sets the SearchableInfo for this SearchView. Properties in the SearchableInfo are used
248     * to display labels, hints, suggestions, create intents for launching search results screens
249     * and controlling other affordances such as a voice button.
250     *
251     * @param searchable a SearchableInfo can be retrieved from the SearchManager, for a specific
252     * activity or a global search provider.
253     */
254    public void setSearchableInfo(SearchableInfo searchable) {
255        mSearchable = searchable;
256        if (mSearchable != null) {
257            updateSearchAutoComplete();
258        }
259        // Cache the voice search capability
260        mVoiceButtonEnabled = hasVoiceSearch();
261        updateViewsVisibility(mIconifiedByDefault);
262    }
263
264    /** @hide */
265    @Override
266    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
267        // Don't accept focus if in the middle of clearing focus
268        if (mClearingFocus) return false;
269        // Check if SearchView is focusable.
270        if (!isFocusable()) return false;
271        // If it is not iconified, then give the focus to the text field
272        if (!isIconified()) {
273            boolean result = mQueryTextView.requestFocus(direction, previouslyFocusedRect);
274            if (result) updateViewsVisibility(false);
275            return result;
276        } else {
277            return super.requestFocus(direction, previouslyFocusedRect);
278        }
279    }
280
281    /** @hide */
282    @Override
283    public void clearFocus() {
284        mClearingFocus = true;
285        super.clearFocus();
286        mQueryTextView.clearFocus();
287        setImeVisibility(false);
288        mClearingFocus = false;
289        updateViewsVisibility(mIconifiedByDefault);
290    }
291
292    /**
293     * Sets a listener for user actions within the SearchView.
294     *
295     * @param listener the listener object that receives callbacks when the user performs
296     * actions in the SearchView such as clicking on buttons or typing a query.
297     */
298    public void setOnQueryTextListener(OnQueryTextListener listener) {
299        mOnQueryChangeListener = listener;
300    }
301
302    /**
303     * Sets a listener to inform when the user closes the SearchView.
304     *
305     * @param listener the listener to call when the user closes the SearchView.
306     */
307    public void setOnCloseListener(OnCloseListener listener) {
308        mOnCloseListener = listener;
309    }
310
311    /**
312     * Sets a listener to inform when the focus of the query text field changes.
313     *
314     * @param listener the listener to inform of focus changes.
315     */
316    public void setOnQueryTextFocusChangeListener(OnFocusChangeListener listener) {
317        mOnQueryTextFocusChangeListener = listener;
318    }
319
320    /**
321     * Sets a listener to inform when a suggestion is focused or clicked.
322     *
323     * @param listener the listener to inform of suggestion selection events.
324     */
325    public void setOnSuggestionListener(OnSuggestionListener listener) {
326        mOnSuggestionListener = listener;
327    }
328
329    /**
330     * Sets a listener to inform when the search button is pressed. This is only
331     * relevant when the text field is not visible by default. Calling {@link #setIconified
332     * setIconified(false)} can also cause this listener to be informed.
333     *
334     * @param listener the listener to inform when the search button is clicked or
335     * the text field is programmatically de-iconified.
336     */
337    public void setOnSearchClickListener(OnClickListener listener) {
338        mOnSearchClickListener = listener;
339    }
340
341    /**
342     * Returns the query string currently in the text field.
343     *
344     * @return the query string
345     */
346    public CharSequence getQuery() {
347        return mQueryTextView.getText();
348    }
349
350    /**
351     * Sets a query string in the text field and optionally submits the query as well.
352     *
353     * @param query the query string. This replaces any query text already present in the
354     * text field.
355     * @param submit whether to submit the query right now or only update the contents of
356     * text field.
357     */
358    public void setQuery(CharSequence query, boolean submit) {
359        mQueryTextView.setText(query);
360        if (query != null) {
361            mQueryTextView.setSelection(query.length());
362        }
363
364        // If the query is not empty and submit is requested, submit the query
365        if (submit && !TextUtils.isEmpty(query)) {
366            onSubmitQuery();
367        }
368    }
369
370    /**
371     * Sets the hint text to display in the query text field. This overrides any hint specified
372     * in the SearchableInfo.
373     *
374     * @param hint the hint text to display
375     *
376     * @attr ref android.R.styleable#SearchView_queryHint
377     */
378    public void setQueryHint(CharSequence hint) {
379        mQueryHint = hint;
380        updateQueryHint();
381    }
382
383    /**
384     * Sets the default or resting state of the search field. If true, a single search icon is
385     * shown by default and expands to show the text field and other buttons when pressed. Also,
386     * if the default state is iconified, then it collapses to that state when the close button
387     * is pressed. Changes to this property will take effect immediately.
388     *
389     * <p>The default value is true.</p>
390     *
391     * @param iconified whether the search field should be iconified by default
392     *
393     * @attr ref android.R.styleable#SearchView_iconifiedByDefault
394     */
395    public void setIconifiedByDefault(boolean iconified) {
396        if (mIconifiedByDefault == iconified) return;
397        mIconifiedByDefault = iconified;
398        updateViewsVisibility(iconified);
399        setImeVisibility(!iconified);
400    }
401
402    /**
403     * Returns the default iconified state of the search field.
404     * @return
405     */
406    public boolean isIconfiedByDefault() {
407        return mIconifiedByDefault;
408    }
409
410    /**
411     * Iconifies or expands the SearchView. Any query text is cleared when iconified. This is
412     * a temporary state and does not override the default iconified state set by
413     * {@link #setIconifiedByDefault(boolean)}. If the default state is iconified, then
414     * a false here will only be valid until the user closes the field. And if the default
415     * state is expanded, then a true here will only clear the text field and not close it.
416     *
417     * @param iconify a true value will collapse the SearchView to an icon, while a false will
418     * expand it.
419     */
420    public void setIconified(boolean iconify) {
421        if (iconify) {
422            onCloseClicked();
423        } else {
424            onSearchClicked();
425        }
426    }
427
428    /**
429     * Returns the current iconified state of the SearchView.
430     *
431     * @return true if the SearchView is currently iconified, false if the search field is
432     * fully visible.
433     */
434    public boolean isIconified() {
435        return mIconified;
436    }
437
438    /**
439     * Enables showing a submit button when the query is non-empty. In cases where the SearchView
440     * is being used to filter the contents of the current activity and doesn't launch a separate
441     * results activity, then the submit button should be disabled.
442     *
443     * @param enabled true to show a submit button for submitting queries, false if a submit
444     * button is not required.
445     */
446    public void setSubmitButtonEnabled(boolean enabled) {
447        mSubmitButtonEnabled = enabled;
448        updateViewsVisibility(isIconified());
449    }
450
451    /**
452     * Returns whether the submit button is enabled when necessary or never displayed.
453     *
454     * @return whether the submit button is enabled automatically when necessary
455     */
456    public boolean isSubmitButtonEnabled() {
457        return mSubmitButtonEnabled;
458    }
459
460    /**
461     * Specifies if a query refinement button should be displayed alongside each suggestion
462     * or if it should depend on the flags set in the individual items retrieved from the
463     * suggestions provider. Clicking on the query refinement button will replace the text
464     * in the query text field with the text from the suggestion. This flag only takes effect
465     * if a SearchableInfo has been specified with {@link #setSearchableInfo(SearchableInfo)}
466     * and not when using a custom adapter.
467     *
468     * @param enable true if all items should have a query refinement button, false if only
469     * those items that have a query refinement flag set should have the button.
470     *
471     * @see SearchManager#SUGGEST_COLUMN_FLAGS
472     * @see SearchManager#FLAG_QUERY_REFINEMENT
473     */
474    public void setQueryRefinementEnabled(boolean enable) {
475        mQueryRefinement = enable;
476        if (mSuggestionsAdapter instanceof SuggestionsAdapter) {
477            ((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement(
478                    enable ? SuggestionsAdapter.REFINE_ALL : SuggestionsAdapter.REFINE_BY_ENTRY);
479        }
480    }
481
482    /**
483     * Returns whether query refinement is enabled for all items or only specific ones.
484     * @return true if enabled for all items, false otherwise.
485     */
486    public boolean isQueryRefinementEnabled() {
487        return mQueryRefinement;
488    }
489
490    /**
491     * You can set a custom adapter if you wish. Otherwise the default adapter is used to
492     * display the suggestions from the suggestions provider associated with the SearchableInfo.
493     *
494     * @see #setSearchableInfo(SearchableInfo)
495     */
496    public void setSuggestionsAdapter(CursorAdapter adapter) {
497        mSuggestionsAdapter = adapter;
498
499        mQueryTextView.setAdapter(mSuggestionsAdapter);
500    }
501
502    /**
503     * Returns the adapter used for suggestions, if any.
504     * @return the suggestions adapter
505     */
506    public CursorAdapter getSuggestionsAdapter() {
507        return mSuggestionsAdapter;
508    }
509
510    /**
511     * Makes the view at most this many pixels wide
512     *
513     * @attr ref android.R.styleable#SearchView_maxWidth
514     */
515    public void setMaxWidth(int maxpixels) {
516        mMaxWidth = maxpixels;
517
518        requestLayout();
519    }
520
521    @Override
522    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
523        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
524        int width = MeasureSpec.getSize(widthMeasureSpec);
525
526        if ((widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.EXACTLY) && mMaxWidth > 0
527                && width > mMaxWidth) {
528            super.onMeasure(MeasureSpec.makeMeasureSpec(mMaxWidth, widthMode), heightMeasureSpec);
529        } else {
530            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
531        }
532    }
533
534    private void updateViewsVisibility(final boolean collapsed) {
535        mIconified = collapsed;
536        // Visibility of views that are visible when collapsed
537        final int visCollapsed = collapsed ? VISIBLE : GONE;
538        // Is there text in the query
539        final boolean hasText = !TextUtils.isEmpty(mQueryTextView.getText());
540
541        mSearchButton.setVisibility(visCollapsed);
542        updateSubmitButton(hasText);
543        mSearchEditFrame.setVisibility(collapsed ? GONE : VISIBLE);
544        updateCloseButton();
545        updateVoiceButton(!hasText);
546        updateSubmitArea();
547    }
548
549    private boolean hasVoiceSearch() {
550        if (mSearchable != null && mSearchable.getVoiceSearchEnabled()) {
551            Intent testIntent = null;
552            if (mSearchable.getVoiceSearchLaunchWebSearch()) {
553                testIntent = mVoiceWebSearchIntent;
554            } else if (mSearchable.getVoiceSearchLaunchRecognizer()) {
555                testIntent = mVoiceAppSearchIntent;
556            }
557            if (testIntent != null) {
558                ResolveInfo ri = getContext().getPackageManager().resolveActivity(testIntent,
559                        PackageManager.MATCH_DEFAULT_ONLY);
560                return ri != null;
561            }
562        }
563        return false;
564    }
565
566    private boolean isSubmitAreaEnabled() {
567        return (mSubmitButtonEnabled || mVoiceButtonEnabled) && !isIconified();
568    }
569
570    private void updateSubmitButton(boolean hasText) {
571        mSubmitButton.setVisibility(
572                isSubmitAreaEnabled() ? (hasText ? VISIBLE : INVISIBLE) : GONE);
573    }
574
575    private void updateSubmitArea() {
576        int visibility = GONE;
577        if (isSubmitAreaEnabled()) {
578            if (mSubmitButton.getVisibility() == VISIBLE
579                    || mVoiceButton.getVisibility() == VISIBLE) {
580                visibility = VISIBLE;
581            } else {
582                visibility = INVISIBLE;
583            }
584        }
585        mSubmitArea.setVisibility(visibility);
586    }
587
588    private void updateCloseButton() {
589        final boolean hasText = !TextUtils.isEmpty(mQueryTextView.getText());
590        // Should we show the close button? It is not shown if there's no focus,
591        // field is not iconified by default and there is no text in it.
592        final boolean showClose = hasText || mIconifiedByDefault || mQueryTextView.hasFocus();
593        mCloseButton.setVisibility(showClose ? VISIBLE : INVISIBLE);
594        mCloseButton.getDrawable().setState(hasText ? ENABLED_STATE_SET : EMPTY_STATE_SET);
595    }
596
597    private void setImeVisibility(boolean visible) {
598        InputMethodManager imm = (InputMethodManager)
599                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
600
601        // We made sure the IME was displayed, so also make sure it is closed
602        // when we go away.
603        if (imm != null) {
604            if (visible) {
605                imm.showSoftInputUnchecked(0, null);
606            } else {
607                imm.hideSoftInputFromWindow(getWindowToken(), 0);
608            }
609        }
610    }
611
612    /**
613     * Called by the SuggestionsAdapter
614     * @hide
615     */
616    /* package */void onQueryRefine(CharSequence queryText) {
617        setQuery(queryText);
618    }
619
620    private final OnClickListener mOnClickListener = new OnClickListener() {
621
622        public void onClick(View v) {
623            if (v == mSearchButton) {
624                onSearchClicked();
625            } else if (v == mCloseButton) {
626                onCloseClicked();
627            } else if (v == mSubmitButton) {
628                onSubmitQuery();
629            } else if (v == mVoiceButton) {
630                onVoiceClicked();
631            }
632        }
633    };
634
635    /**
636     * Handles the key down event for dealing with action keys.
637     *
638     * @param keyCode This is the keycode of the typed key, and is the same value as
639     *        found in the KeyEvent parameter.
640     * @param event The complete event record for the typed key
641     *
642     * @return true if the event was handled here, or false if not.
643     */
644    @Override
645    public boolean onKeyDown(int keyCode, KeyEvent event) {
646        if (mSearchable == null) {
647            return false;
648        }
649
650        // if it's an action specified by the searchable activity, launch the
651        // entered query with the action key
652        SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
653        if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) {
654            launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView.getText()
655                    .toString());
656            return true;
657        }
658
659        return super.onKeyDown(keyCode, event);
660    }
661
662    /**
663     * React to the user typing "enter" or other hardwired keys while typing in
664     * the search box. This handles these special keys while the edit box has
665     * focus.
666     */
667    View.OnKeyListener mTextKeyListener = new View.OnKeyListener() {
668        public boolean onKey(View v, int keyCode, KeyEvent event) {
669            // guard against possible race conditions
670            if (mSearchable == null) {
671                return false;
672            }
673
674            if (DBG) {
675                Log.d(LOG_TAG, "mTextListener.onKey(" + keyCode + "," + event + "), selection: "
676                        + mQueryTextView.getListSelection());
677            }
678
679            // If a suggestion is selected, handle enter, search key, and action keys
680            // as presses on the selected suggestion
681            if (mQueryTextView.isPopupShowing()
682                    && mQueryTextView.getListSelection() != ListView.INVALID_POSITION) {
683                return onSuggestionsKey(v, keyCode, event);
684            }
685
686            // If there is text in the query box, handle enter, and action keys
687            // The search key is handled by the dialog's onKeyDown().
688            if (!mQueryTextView.isEmpty() && event.hasNoModifiers()) {
689                if (event.getAction() == KeyEvent.ACTION_UP) {
690                    if (keyCode == KeyEvent.KEYCODE_ENTER) {
691                        v.cancelLongPress();
692
693                        // Launch as a regular search.
694                        launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, mQueryTextView.getText()
695                                .toString());
696                        return true;
697                    }
698                }
699                if (event.getAction() == KeyEvent.ACTION_DOWN) {
700                    SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
701                    if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) {
702                        launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView
703                                .getText().toString());
704                        return true;
705                    }
706                }
707            }
708            return false;
709        }
710    };
711
712    /**
713     * React to the user typing while in the suggestions list. First, check for
714     * action keys. If not handled, try refocusing regular characters into the
715     * EditText.
716     */
717    private boolean onSuggestionsKey(View v, int keyCode, KeyEvent event) {
718        // guard against possible race conditions (late arrival after dismiss)
719        if (mSearchable == null) {
720            return false;
721        }
722        if (mSuggestionsAdapter == null) {
723            return false;
724        }
725        if (event.getAction() == KeyEvent.ACTION_DOWN && event.hasNoModifiers()) {
726            // First, check for enter or search (both of which we'll treat as a
727            // "click")
728            if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH
729                    || keyCode == KeyEvent.KEYCODE_TAB) {
730                int position = mQueryTextView.getListSelection();
731                return onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null);
732            }
733
734            // Next, check for left/right moves, which we use to "return" the
735            // user to the edit view
736            if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
737                // give "focus" to text editor, with cursor at the beginning if
738                // left key, at end if right key
739                // TODO: Reverse left/right for right-to-left languages, e.g.
740                // Arabic
741                int selPoint = (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) ? 0 : mQueryTextView
742                        .length();
743                mQueryTextView.setSelection(selPoint);
744                mQueryTextView.setListSelection(0);
745                mQueryTextView.clearListSelection();
746                mQueryTextView.ensureImeVisible(true);
747
748                return true;
749            }
750
751            // Next, check for an "up and out" move
752            if (keyCode == KeyEvent.KEYCODE_DPAD_UP && 0 == mQueryTextView.getListSelection()) {
753                // TODO: restoreUserQuery();
754                // let ACTV complete the move
755                return false;
756            }
757
758            // Next, check for an "action key"
759            SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
760            if ((actionKey != null)
761                    && ((actionKey.getSuggestActionMsg() != null) || (actionKey
762                            .getSuggestActionMsgColumn() != null))) {
763                // launch suggestion using action key column
764                int position = mQueryTextView.getListSelection();
765                if (position != ListView.INVALID_POSITION) {
766                    Cursor c = mSuggestionsAdapter.getCursor();
767                    if (c.moveToPosition(position)) {
768                        final String actionMsg = getActionKeyMessage(c, actionKey);
769                        if (actionMsg != null && (actionMsg.length() > 0)) {
770                            return onItemClicked(position, keyCode, actionMsg);
771                        }
772                    }
773                }
774            }
775        }
776        return false;
777    }
778
779    /**
780     * For a given suggestion and a given cursor row, get the action message. If
781     * not provided by the specific row/column, also check for a single
782     * definition (for the action key).
783     *
784     * @param c The cursor providing suggestions
785     * @param actionKey The actionkey record being examined
786     *
787     * @return Returns a string, or null if no action key message for this
788     *         suggestion
789     */
790    private static String getActionKeyMessage(Cursor c, SearchableInfo.ActionKeyInfo actionKey) {
791        String result = null;
792        // check first in the cursor data, for a suggestion-specific message
793        final String column = actionKey.getSuggestActionMsgColumn();
794        if (column != null) {
795            result = SuggestionsAdapter.getColumnString(c, column);
796        }
797        // If the cursor didn't give us a message, see if there's a single
798        // message defined
799        // for the actionkey (for all suggestions)
800        if (result == null) {
801            result = actionKey.getSuggestActionMsg();
802        }
803        return result;
804    }
805
806    private void updateQueryHint() {
807        if (mQueryHint != null) {
808            mQueryTextView.setHint(mQueryHint);
809        } else if (mSearchable != null) {
810            CharSequence hint = null;
811            int hintId = mSearchable.getHintId();
812            if (hintId != 0) {
813                hint = getContext().getString(hintId);
814            }
815            if (hint != null) {
816                mQueryTextView.setHint(hint);
817            }
818        }
819    }
820
821    /**
822     * Updates the auto-complete text view.
823     */
824    private void updateSearchAutoComplete() {
825        // close any existing suggestions adapter
826        //closeSuggestionsAdapter();
827
828        mQueryTextView.setDropDownAnimationStyle(0); // no animation
829        mQueryTextView.setThreshold(mSearchable.getSuggestThreshold());
830
831        // attach the suggestions adapter, if suggestions are available
832        // The existence of a suggestions authority is the proxy for "suggestions available here"
833        if (mSearchable.getSuggestAuthority() != null) {
834            mSuggestionsAdapter = new SuggestionsAdapter(getContext(),
835                    this, mSearchable, mOutsideDrawablesCache);
836            mQueryTextView.setAdapter(mSuggestionsAdapter);
837            ((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement(
838                    mQueryRefinement ? SuggestionsAdapter.REFINE_ALL
839                    : SuggestionsAdapter.REFINE_BY_ENTRY);
840        }
841    }
842
843    /**
844     * Update the visibility of the voice button.  There are actually two voice search modes,
845     * either of which will activate the button.
846     * @param empty whether the search query text field is empty. If it is, then the other
847     * criteria apply to make the voice button visible. Otherwise the voice button will not
848     * be visible - i.e., if the user has typed a query, remove the voice button.
849     */
850    private void updateVoiceButton(boolean empty) {
851        // If the voice button is to be visible, show it
852        // Else, make it gone if the submit button is enabled, otherwise invisible to
853        // avoid losing the real-estate
854        int visibility = mSubmitButtonEnabled ? GONE : INVISIBLE;
855
856        if (mVoiceButtonEnabled && !isIconified() && empty) {
857            visibility = VISIBLE;
858            mSubmitButton.setVisibility(GONE);
859        }
860        mVoiceButton.setVisibility(visibility);
861    }
862
863    private final OnEditorActionListener mOnEditorActionListener = new OnEditorActionListener() {
864
865        /**
866         * Called when the input method default action key is pressed.
867         */
868        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
869            onSubmitQuery();
870            return true;
871        }
872    };
873
874    private void onTextChanged(CharSequence newText) {
875        CharSequence text = mQueryTextView.getText();
876        boolean hasText = !TextUtils.isEmpty(text);
877        if (isSubmitButtonEnabled()) {
878            updateSubmitButton(hasText);
879        }
880        updateVoiceButton(!hasText);
881        updateCloseButton();
882        updateSubmitArea();
883        if (mOnQueryChangeListener != null) {
884            mOnQueryChangeListener.onQueryTextChange(newText.toString());
885        }
886    }
887
888    private void onSubmitQuery() {
889        CharSequence query = mQueryTextView.getText();
890        if (!TextUtils.isEmpty(query)) {
891            if (mOnQueryChangeListener == null
892                    || !mOnQueryChangeListener.onQueryTextSubmit(query.toString())) {
893                if (mSearchable != null) {
894                    launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString());
895                    setImeVisibility(false);
896                }
897                dismissSuggestions();
898            }
899        }
900    }
901
902    private void dismissSuggestions() {
903        mQueryTextView.dismissDropDown();
904    }
905
906    private void onCloseClicked() {
907        if (mOnCloseListener == null || !mOnCloseListener.onClose()) {
908            CharSequence text = mQueryTextView.getText();
909            if (TextUtils.isEmpty(text)) {
910                // query field already empty, hide the keyboard and remove focus
911                clearFocus();
912                setImeVisibility(false);
913            } else {
914                mQueryTextView.setText("");
915            }
916            updateViewsVisibility(mIconifiedByDefault);
917            if (mIconifiedByDefault) setImeVisibility(false);
918        }
919    }
920
921    private void onSearchClicked() {
922        updateViewsVisibility(false);
923        mQueryTextView.requestFocus();
924        setImeVisibility(true);
925        if (mOnSearchClickListener != null) {
926            mOnSearchClickListener.onClick(this);
927        }
928    }
929
930    private void onVoiceClicked() {
931        // guard against possible race conditions
932        if (mSearchable == null) {
933            return;
934        }
935        SearchableInfo searchable = mSearchable;
936        try {
937            if (searchable.getVoiceSearchLaunchWebSearch()) {
938                Intent webSearchIntent = createVoiceWebSearchIntent(mVoiceWebSearchIntent,
939                        searchable);
940                getContext().startActivity(webSearchIntent);
941            } else if (searchable.getVoiceSearchLaunchRecognizer()) {
942                Intent appSearchIntent = createVoiceAppSearchIntent(mVoiceAppSearchIntent,
943                        searchable);
944                getContext().startActivity(appSearchIntent);
945            }
946        } catch (ActivityNotFoundException e) {
947            // Should not happen, since we check the availability of
948            // voice search before showing the button. But just in case...
949            Log.w(LOG_TAG, "Could not find voice search activity");
950        }
951    }
952
953    void onTextFocusChanged() {
954        updateCloseButton();
955    }
956
957    private boolean onItemClicked(int position, int actionKey, String actionMsg) {
958        if (mOnSuggestionListener == null
959                || !mOnSuggestionListener.onSuggestionClick(position)) {
960            launchSuggestion(position, KeyEvent.KEYCODE_UNKNOWN, null);
961            setImeVisibility(false);
962            dismissSuggestions();
963            return true;
964        }
965        return false;
966    }
967
968    private boolean onItemSelected(int position) {
969        if (mOnSuggestionListener == null
970                || !mOnSuggestionListener.onSuggestionSelect(position)) {
971            rewriteQueryFromSuggestion(position);
972            return true;
973        }
974        return false;
975    }
976
977    private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
978
979        /**
980         * Implements OnItemClickListener
981         */
982        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
983            if (DBG) Log.d(LOG_TAG, "onItemClick() position " + position);
984            onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null);
985        }
986    };
987
988    private final OnItemSelectedListener mOnItemSelectedListener = new OnItemSelectedListener() {
989
990        /**
991         * Implements OnItemSelectedListener
992         */
993        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
994            if (DBG) Log.d(LOG_TAG, "onItemSelected() position " + position);
995            SearchView.this.onItemSelected(position);
996        }
997
998        /**
999         * Implements OnItemSelectedListener
1000         */
1001        public void onNothingSelected(AdapterView<?> parent) {
1002            if (DBG)
1003                Log.d(LOG_TAG, "onNothingSelected()");
1004        }
1005    };
1006
1007    /**
1008     * Query rewriting.
1009     */
1010    private void rewriteQueryFromSuggestion(int position) {
1011        CharSequence oldQuery = mQueryTextView.getText();
1012        Cursor c = mSuggestionsAdapter.getCursor();
1013        if (c == null) {
1014            return;
1015        }
1016        if (c.moveToPosition(position)) {
1017            // Get the new query from the suggestion.
1018            CharSequence newQuery = mSuggestionsAdapter.convertToString(c);
1019            if (newQuery != null) {
1020                // The suggestion rewrites the query.
1021                // Update the text field, without getting new suggestions.
1022                setQuery(newQuery);
1023            } else {
1024                // The suggestion does not rewrite the query, restore the user's query.
1025                setQuery(oldQuery);
1026            }
1027        } else {
1028            // We got a bad position, restore the user's query.
1029            setQuery(oldQuery);
1030        }
1031    }
1032
1033    /**
1034     * Launches an intent based on a suggestion.
1035     *
1036     * @param position The index of the suggestion to create the intent from.
1037     * @param actionKey The key code of the action key that was pressed,
1038     *        or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
1039     * @param actionMsg The message for the action key that was pressed,
1040     *        or <code>null</code> if none.
1041     * @return true if a successful launch, false if could not (e.g. bad position).
1042     */
1043    private boolean launchSuggestion(int position, int actionKey, String actionMsg) {
1044        Cursor c = mSuggestionsAdapter.getCursor();
1045        if ((c != null) && c.moveToPosition(position)) {
1046
1047            Intent intent = createIntentFromSuggestion(c, actionKey, actionMsg);
1048
1049            // launch the intent
1050            launchIntent(intent);
1051
1052            return true;
1053        }
1054        return false;
1055    }
1056
1057    /**
1058     * Launches an intent, including any special intent handling.
1059     */
1060    private void launchIntent(Intent intent) {
1061        if (intent == null) {
1062            return;
1063        }
1064        try {
1065            // If the intent was created from a suggestion, it will always have an explicit
1066            // component here.
1067            getContext().startActivity(intent);
1068        } catch (RuntimeException ex) {
1069            Log.e(LOG_TAG, "Failed launch activity: " + intent, ex);
1070        }
1071    }
1072
1073    /**
1074     * Sets the text in the query box, without updating the suggestions.
1075     */
1076    private void setQuery(CharSequence query) {
1077        mQueryTextView.setText(query, true);
1078        // Move the cursor to the end
1079        mQueryTextView.setSelection(TextUtils.isEmpty(query) ? 0 : query.length());
1080    }
1081
1082    private void launchQuerySearch(int actionKey, String actionMsg, String query) {
1083        String action = Intent.ACTION_SEARCH;
1084        Intent intent = createIntent(action, null, null, query, actionKey, actionMsg);
1085        getContext().startActivity(intent);
1086    }
1087
1088    /**
1089     * Constructs an intent from the given information and the search dialog state.
1090     *
1091     * @param action Intent action.
1092     * @param data Intent data, or <code>null</code>.
1093     * @param extraData Data for {@link SearchManager#EXTRA_DATA_KEY} or <code>null</code>.
1094     * @param query Intent query, or <code>null</code>.
1095     * @param actionKey The key code of the action key that was pressed,
1096     *        or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
1097     * @param actionMsg The message for the action key that was pressed,
1098     *        or <code>null</code> if none.
1099     * @param mode The search mode, one of the acceptable values for
1100     *             {@link SearchManager#SEARCH_MODE}, or {@code null}.
1101     * @return The intent.
1102     */
1103    private Intent createIntent(String action, Uri data, String extraData, String query,
1104            int actionKey, String actionMsg) {
1105        // Now build the Intent
1106        Intent intent = new Intent(action);
1107        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1108        // We need CLEAR_TOP to avoid reusing an old task that has other activities
1109        // on top of the one we want. We don't want to do this in in-app search though,
1110        // as it can be destructive to the activity stack.
1111        if (data != null) {
1112            intent.setData(data);
1113        }
1114        intent.putExtra(SearchManager.USER_QUERY, query);
1115        if (query != null) {
1116            intent.putExtra(SearchManager.QUERY, query);
1117        }
1118        if (extraData != null) {
1119            intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
1120        }
1121        if (actionKey != KeyEvent.KEYCODE_UNKNOWN) {
1122            intent.putExtra(SearchManager.ACTION_KEY, actionKey);
1123            intent.putExtra(SearchManager.ACTION_MSG, actionMsg);
1124        }
1125        intent.setComponent(mSearchable.getSearchActivity());
1126        return intent;
1127    }
1128
1129    /**
1130     * Create and return an Intent that can launch the voice search activity for web search.
1131     */
1132    private Intent createVoiceWebSearchIntent(Intent baseIntent, SearchableInfo searchable) {
1133        Intent voiceIntent = new Intent(baseIntent);
1134        ComponentName searchActivity = searchable.getSearchActivity();
1135        voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null
1136                : searchActivity.flattenToShortString());
1137        return voiceIntent;
1138    }
1139
1140    /**
1141     * Create and return an Intent that can launch the voice search activity, perform a specific
1142     * voice transcription, and forward the results to the searchable activity.
1143     *
1144     * @param baseIntent The voice app search intent to start from
1145     * @return A completely-configured intent ready to send to the voice search activity
1146     */
1147    private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) {
1148        ComponentName searchActivity = searchable.getSearchActivity();
1149
1150        // create the necessary intent to set up a search-and-forward operation
1151        // in the voice search system.   We have to keep the bundle separate,
1152        // because it becomes immutable once it enters the PendingIntent
1153        Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
1154        queryIntent.setComponent(searchActivity);
1155        PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent,
1156                PendingIntent.FLAG_ONE_SHOT);
1157
1158        // Now set up the bundle that will be inserted into the pending intent
1159        // when it's time to do the search.  We always build it here (even if empty)
1160        // because the voice search activity will always need to insert "QUERY" into
1161        // it anyway.
1162        Bundle queryExtras = new Bundle();
1163
1164        // Now build the intent to launch the voice search.  Add all necessary
1165        // extras to launch the voice recognizer, and then all the necessary extras
1166        // to forward the results to the searchable activity
1167        Intent voiceIntent = new Intent(baseIntent);
1168
1169        // Add all of the configuration options supplied by the searchable's metadata
1170        String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM;
1171        String prompt = null;
1172        String language = null;
1173        int maxResults = 1;
1174
1175        Resources resources = getResources();
1176        if (searchable.getVoiceLanguageModeId() != 0) {
1177            languageModel = resources.getString(searchable.getVoiceLanguageModeId());
1178        }
1179        if (searchable.getVoicePromptTextId() != 0) {
1180            prompt = resources.getString(searchable.getVoicePromptTextId());
1181        }
1182        if (searchable.getVoiceLanguageId() != 0) {
1183            language = resources.getString(searchable.getVoiceLanguageId());
1184        }
1185        if (searchable.getVoiceMaxResults() != 0) {
1186            maxResults = searchable.getVoiceMaxResults();
1187        }
1188        voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel);
1189        voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
1190        voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
1191        voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
1192        voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null
1193                : searchActivity.flattenToShortString());
1194
1195        // Add the values that configure forwarding the results
1196        voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
1197        voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);
1198
1199        return voiceIntent;
1200    }
1201
1202    /**
1203     * When a particular suggestion has been selected, perform the various lookups required
1204     * to use the suggestion.  This includes checking the cursor for suggestion-specific data,
1205     * and/or falling back to the XML for defaults;  It also creates REST style Uri data when
1206     * the suggestion includes a data id.
1207     *
1208     * @param c The suggestions cursor, moved to the row of the user's selection
1209     * @param actionKey The key code of the action key that was pressed,
1210     *        or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
1211     * @param actionMsg The message for the action key that was pressed,
1212     *        or <code>null</code> if none.
1213     * @return An intent for the suggestion at the cursor's position.
1214     */
1215    private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) {
1216        try {
1217            // use specific action if supplied, or default action if supplied, or fixed default
1218            String action = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION);
1219
1220            if (action == null) {
1221                action = mSearchable.getSuggestIntentAction();
1222            }
1223            if (action == null) {
1224                action = Intent.ACTION_SEARCH;
1225            }
1226
1227            // use specific data if supplied, or default data if supplied
1228            String data = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA);
1229            if (data == null) {
1230                data = mSearchable.getSuggestIntentData();
1231            }
1232            // then, if an ID was provided, append it.
1233            if (data != null) {
1234                String id = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
1235                if (id != null) {
1236                    data = data + "/" + Uri.encode(id);
1237                }
1238            }
1239            Uri dataUri = (data == null) ? null : Uri.parse(data);
1240
1241            String query = getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY);
1242            String extraData = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
1243
1244            return createIntent(action, dataUri, extraData, query, actionKey, actionMsg);
1245        } catch (RuntimeException e ) {
1246            int rowNum;
1247            try {                       // be really paranoid now
1248                rowNum = c.getPosition();
1249            } catch (RuntimeException e2 ) {
1250                rowNum = -1;
1251            }
1252            Log.w(LOG_TAG, "Search Suggestions cursor at row " + rowNum +
1253                            " returned exception" + e.toString());
1254            return null;
1255        }
1256    }
1257
1258    static boolean isLandscapeMode(Context context) {
1259        return context.getResources().getConfiguration().orientation
1260                == Configuration.ORIENTATION_LANDSCAPE;
1261    }
1262
1263    /**
1264     * Callback to watch the text field for empty/non-empty
1265     */
1266    private TextWatcher mTextWatcher = new TextWatcher() {
1267
1268        public void beforeTextChanged(CharSequence s, int start, int before, int after) { }
1269
1270        public void onTextChanged(CharSequence s, int start,
1271                int before, int after) {
1272            SearchView.this.onTextChanged(s);
1273        }
1274
1275        public void afterTextChanged(Editable s) {
1276        }
1277    };
1278
1279    /**
1280     * Local subclass for AutoCompleteTextView.
1281     * @hide
1282     */
1283    public static class SearchAutoComplete extends AutoCompleteTextView {
1284
1285        private int mThreshold;
1286        private SearchView mSearchView;
1287
1288        public SearchAutoComplete(Context context) {
1289            super(context);
1290            mThreshold = getThreshold();
1291        }
1292
1293        public SearchAutoComplete(Context context, AttributeSet attrs) {
1294            super(context, attrs);
1295            mThreshold = getThreshold();
1296        }
1297
1298        public SearchAutoComplete(Context context, AttributeSet attrs, int defStyle) {
1299            super(context, attrs, defStyle);
1300            mThreshold = getThreshold();
1301        }
1302
1303        void setSearchView(SearchView searchView) {
1304            mSearchView = searchView;
1305        }
1306
1307        @Override
1308        public void setThreshold(int threshold) {
1309            super.setThreshold(threshold);
1310            mThreshold = threshold;
1311        }
1312
1313        /**
1314         * Returns true if the text field is empty, or contains only whitespace.
1315         */
1316        private boolean isEmpty() {
1317            return TextUtils.getTrimmedLength(getText()) == 0;
1318        }
1319
1320        /**
1321         * We override this method to avoid replacing the query box text when a
1322         * suggestion is clicked.
1323         */
1324        @Override
1325        protected void replaceText(CharSequence text) {
1326        }
1327
1328        /**
1329         * We override this method to avoid an extra onItemClick being called on
1330         * the drop-down's OnItemClickListener by
1331         * {@link AutoCompleteTextView#onKeyUp(int, KeyEvent)} when an item is
1332         * clicked with the trackball.
1333         */
1334        @Override
1335        public void performCompletion() {
1336        }
1337
1338        /**
1339         * We override this method to be sure and show the soft keyboard if
1340         * appropriate when the TextView has focus.
1341         */
1342        @Override
1343        public void onWindowFocusChanged(boolean hasWindowFocus) {
1344            super.onWindowFocusChanged(hasWindowFocus);
1345
1346            if (hasWindowFocus && mSearchView.hasFocus() && getVisibility() == VISIBLE) {
1347                InputMethodManager inputManager = (InputMethodManager) getContext()
1348                        .getSystemService(Context.INPUT_METHOD_SERVICE);
1349                inputManager.showSoftInput(this, 0);
1350                // If in landscape mode, then make sure that
1351                // the ime is in front of the dropdown.
1352                if (isLandscapeMode(getContext())) {
1353                    ensureImeVisible(true);
1354                }
1355            }
1356        }
1357
1358        @Override
1359        protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
1360            super.onFocusChanged(focused, direction, previouslyFocusedRect);
1361            mSearchView.onTextFocusChanged();
1362        }
1363
1364        /**
1365         * We override this method so that we can allow a threshold of zero,
1366         * which ACTV does not.
1367         */
1368        @Override
1369        public boolean enoughToFilter() {
1370            return mThreshold <= 0 || super.enoughToFilter();
1371        }
1372    }
1373}
1374