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