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