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