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