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