SearchView.java revision 4aedb39a49bda340f871c8fac2239de4fe549b03
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()) {
627                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
628                    v.cancelLongPress();
629
630                    // Launch as a regular search.
631                    launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, mQueryTextView.getText()
632                            .toString());
633                    return true;
634                }
635                if (event.getAction() == KeyEvent.ACTION_DOWN) {
636                    SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
637                    if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) {
638                        launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView
639                                .getText().toString());
640                        return true;
641                    }
642                }
643            }
644            return false;
645        }
646    };
647
648    /**
649     * React to the user typing while in the suggestions list. First, check for
650     * action keys. If not handled, try refocusing regular characters into the
651     * EditText.
652     */
653    private boolean onSuggestionsKey(View v, int keyCode, KeyEvent event) {
654        // guard against possible race conditions (late arrival after dismiss)
655        if (mSearchable == null) {
656            return false;
657        }
658        if (mSuggestionsAdapter == null) {
659            return false;
660        }
661        if (event.getAction() == KeyEvent.ACTION_DOWN) {
662
663            // First, check for enter or search (both of which we'll treat as a
664            // "click")
665            if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH) {
666                int position = mQueryTextView.getListSelection();
667                return onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null);
668            }
669
670            // Next, check for left/right moves, which we use to "return" the
671            // user to the edit view
672            if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
673                // give "focus" to text editor, with cursor at the beginning if
674                // left key, at end if right key
675                // TODO: Reverse left/right for right-to-left languages, e.g.
676                // Arabic
677                int selPoint = (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) ? 0 : mQueryTextView
678                        .length();
679                mQueryTextView.setSelection(selPoint);
680                mQueryTextView.setListSelection(0);
681                mQueryTextView.clearListSelection();
682                mQueryTextView.ensureImeVisible(true);
683
684                return true;
685            }
686
687            // Next, check for an "up and out" move
688            if (keyCode == KeyEvent.KEYCODE_DPAD_UP && 0 == mQueryTextView.getListSelection()) {
689                // TODO: restoreUserQuery();
690                // let ACTV complete the move
691                return false;
692            }
693
694            // Next, check for an "action key"
695            SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
696            if ((actionKey != null)
697                    && ((actionKey.getSuggestActionMsg() != null) || (actionKey
698                            .getSuggestActionMsgColumn() != null))) {
699                // launch suggestion using action key column
700                int position = mQueryTextView.getListSelection();
701                if (position != ListView.INVALID_POSITION) {
702                    Cursor c = mSuggestionsAdapter.getCursor();
703                    if (c.moveToPosition(position)) {
704                        final String actionMsg = getActionKeyMessage(c, actionKey);
705                        if (actionMsg != null && (actionMsg.length() > 0)) {
706                            return onItemClicked(position, keyCode, actionMsg);
707                        }
708                    }
709                }
710            }
711        }
712        return false;
713    }
714
715    /**
716     * For a given suggestion and a given cursor row, get the action message. If
717     * not provided by the specific row/column, also check for a single
718     * definition (for the action key).
719     *
720     * @param c The cursor providing suggestions
721     * @param actionKey The actionkey record being examined
722     *
723     * @return Returns a string, or null if no action key message for this
724     *         suggestion
725     */
726    private static String getActionKeyMessage(Cursor c, SearchableInfo.ActionKeyInfo actionKey) {
727        String result = null;
728        // check first in the cursor data, for a suggestion-specific message
729        final String column = actionKey.getSuggestActionMsgColumn();
730        if (column != null) {
731            result = SuggestionsAdapter.getColumnString(c, column);
732        }
733        // If the cursor didn't give us a message, see if there's a single
734        // message defined
735        // for the actionkey (for all suggestions)
736        if (result == null) {
737            result = actionKey.getSuggestActionMsg();
738        }
739        return result;
740    }
741
742    private void updateQueryHint() {
743        if (mQueryHint != null) {
744            mQueryTextView.setHint(mQueryHint);
745        } else if (mSearchable != null) {
746            CharSequence hint = null;
747            int hintId = mSearchable.getHintId();
748            if (hintId != 0) {
749                hint = getContext().getString(hintId);
750            }
751            if (hint != null) {
752                mQueryTextView.setHint(hint);
753            }
754        }
755    }
756
757    /**
758     * Updates the auto-complete text view.
759     */
760    private void updateSearchAutoComplete() {
761        // close any existing suggestions adapter
762        //closeSuggestionsAdapter();
763
764        mQueryTextView.setDropDownAnimationStyle(0); // no animation
765        mQueryTextView.setThreshold(mSearchable.getSuggestThreshold());
766
767        // attach the suggestions adapter, if suggestions are available
768        // The existence of a suggestions authority is the proxy for "suggestions available here"
769        if (mSearchable.getSuggestAuthority() != null) {
770            mSuggestionsAdapter = new SuggestionsAdapter(getContext(),
771                    this, mSearchable, mOutsideDrawablesCache);
772            mQueryTextView.setAdapter(mSuggestionsAdapter);
773            ((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement(
774                    mQueryRefinement ? SuggestionsAdapter.REFINE_ALL
775                    : SuggestionsAdapter.REFINE_BY_ENTRY);
776        }
777    }
778
779    /**
780     * Update the visibility of the voice button.  There are actually two voice search modes,
781     * either of which will activate the button.
782     * @param empty whether the search query text field is empty. If it is, then the other
783     * criteria apply to make the voice button visible. Otherwise the voice button will not
784     * be visible - i.e., if the user has typed a query, remove the voice button.
785     */
786    private void updateVoiceButton(boolean empty) {
787        int visibility = View.GONE;
788        if (mSearchable != null && mSearchable.getVoiceSearchEnabled() && empty
789                && !isIconified()) {
790            Intent testIntent = null;
791            if (mSearchable.getVoiceSearchLaunchWebSearch()) {
792                testIntent = mVoiceWebSearchIntent;
793            } else if (mSearchable.getVoiceSearchLaunchRecognizer()) {
794                testIntent = mVoiceAppSearchIntent;
795            }
796            if (testIntent != null) {
797                ResolveInfo ri = getContext().getPackageManager().resolveActivity(testIntent,
798                        PackageManager.MATCH_DEFAULT_ONLY);
799                if (ri != null) {
800                    visibility = View.VISIBLE;
801                }
802            }
803        }
804        mVoiceButton.setVisibility(visibility);
805    }
806
807    private final OnEditorActionListener mOnEditorActionListener = new OnEditorActionListener() {
808
809        /**
810         * Called when the input method default action key is pressed.
811         */
812        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
813            onSubmitQuery();
814            return true;
815        }
816    };
817
818    private void onTextChanged(CharSequence newText) {
819        CharSequence text = mQueryTextView.getText();
820        boolean hasText = !TextUtils.isEmpty(text);
821        if (isSubmitButtonEnabled()) {
822            mSubmitButton.setVisibility(hasText ? VISIBLE : GONE);
823            requestLayout();
824            invalidate();
825        }
826        updateVoiceButton(!hasText);
827        updateViewsVisibility(mIconifiedByDefault);
828        if (mOnQueryChangeListener != null) {
829            mOnQueryChangeListener.onQueryTextChanged(newText.toString());
830        }
831    }
832
833    private void onSubmitQuery() {
834        CharSequence query = mQueryTextView.getText();
835        if (!TextUtils.isEmpty(query)) {
836            if (mOnQueryChangeListener == null
837                    || !mOnQueryChangeListener.onSubmitQuery(query.toString())) {
838                if (mSearchable != null) {
839                    launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString());
840                    setImeVisibility(false);
841                }
842                dismissSuggestions();
843            }
844        }
845    }
846
847    private void dismissSuggestions() {
848        mQueryTextView.dismissDropDown();
849    }
850
851    private void onCloseClicked() {
852        if (mOnCloseListener == null || !mOnCloseListener.onClose()) {
853            CharSequence text = mQueryTextView.getText();
854            if (TextUtils.isEmpty(text)) {
855                // query field already empty, hide the keyboard and remove focus
856                clearFocus();
857                setImeVisibility(false);
858            } else {
859                mQueryTextView.setText("");
860            }
861            updateViewsVisibility(mIconifiedByDefault);
862            if (mIconifiedByDefault) setImeVisibility(false);
863        }
864    }
865
866    private void onSearchClicked() {
867        mQueryTextView.requestFocus();
868        updateViewsVisibility(false);
869        setImeVisibility(true);
870        if (mOnSearchClickListener != null) {
871            mOnSearchClickListener.onClick(this);
872        }
873    }
874
875    private void onVoiceClicked() {
876        // guard against possible race conditions
877        if (mSearchable == null) {
878            return;
879        }
880        SearchableInfo searchable = mSearchable;
881        try {
882            if (searchable.getVoiceSearchLaunchWebSearch()) {
883                Intent webSearchIntent = createVoiceWebSearchIntent(mVoiceWebSearchIntent,
884                        searchable);
885                getContext().startActivity(webSearchIntent);
886            } else if (searchable.getVoiceSearchLaunchRecognizer()) {
887                Intent appSearchIntent = createVoiceAppSearchIntent(mVoiceAppSearchIntent,
888                        searchable);
889                getContext().startActivity(appSearchIntent);
890            }
891        } catch (ActivityNotFoundException e) {
892            // Should not happen, since we check the availability of
893            // voice search before showing the button. But just in case...
894            Log.w(LOG_TAG, "Could not find voice search activity");
895        }
896    }
897
898    void onTextFocusChanged() {
899        updateCloseButton();
900    }
901
902    private boolean onItemClicked(int position, int actionKey, String actionMsg) {
903        if (mOnSuggestionListener == null
904                || !mOnSuggestionListener.onSuggestionClicked(position)) {
905            launchSuggestion(position, KeyEvent.KEYCODE_UNKNOWN, null);
906            setImeVisibility(false);
907            dismissSuggestions();
908            return true;
909        }
910        return false;
911    }
912
913    private boolean onItemSelected(int position) {
914        if (mOnSuggestionListener == null
915                || !mOnSuggestionListener.onSuggestionSelected(position)) {
916            rewriteQueryFromSuggestion(position);
917            return true;
918        }
919        return false;
920    }
921
922    private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
923
924        /**
925         * Implements OnItemClickListener
926         */
927        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
928            if (DBG) Log.d(LOG_TAG, "onItemClick() position " + position);
929            onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null);
930        }
931    };
932
933    private final OnItemSelectedListener mOnItemSelectedListener = new OnItemSelectedListener() {
934
935        /**
936         * Implements OnItemSelectedListener
937         */
938        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
939            if (DBG) Log.d(LOG_TAG, "onItemSelected() position " + position);
940            SearchView.this.onItemSelected(position);
941        }
942
943        /**
944         * Implements OnItemSelectedListener
945         */
946        public void onNothingSelected(AdapterView<?> parent) {
947            if (DBG)
948                Log.d(LOG_TAG, "onNothingSelected()");
949        }
950    };
951
952    /**
953     * Query rewriting.
954     */
955    private void rewriteQueryFromSuggestion(int position) {
956        CharSequence oldQuery = mQueryTextView.getText();
957        Cursor c = mSuggestionsAdapter.getCursor();
958        if (c == null) {
959            return;
960        }
961        if (c.moveToPosition(position)) {
962            // Get the new query from the suggestion.
963            CharSequence newQuery = mSuggestionsAdapter.convertToString(c);
964            if (newQuery != null) {
965                // The suggestion rewrites the query.
966                // Update the text field, without getting new suggestions.
967                setQuery(newQuery);
968            } else {
969                // The suggestion does not rewrite the query, restore the user's query.
970                setQuery(oldQuery);
971            }
972        } else {
973            // We got a bad position, restore the user's query.
974            setQuery(oldQuery);
975        }
976    }
977
978    /**
979     * Launches an intent based on a suggestion.
980     *
981     * @param position The index of the suggestion to create the intent from.
982     * @param actionKey The key code of the action key that was pressed,
983     *        or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
984     * @param actionMsg The message for the action key that was pressed,
985     *        or <code>null</code> if none.
986     * @return true if a successful launch, false if could not (e.g. bad position).
987     */
988    private boolean launchSuggestion(int position, int actionKey, String actionMsg) {
989        Cursor c = mSuggestionsAdapter.getCursor();
990        if ((c != null) && c.moveToPosition(position)) {
991
992            Intent intent = createIntentFromSuggestion(c, actionKey, actionMsg);
993
994            // launch the intent
995            launchIntent(intent);
996
997            return true;
998        }
999        return false;
1000    }
1001
1002    /**
1003     * Launches an intent, including any special intent handling.
1004     */
1005    private void launchIntent(Intent intent) {
1006        if (intent == null) {
1007            return;
1008        }
1009        try {
1010            // If the intent was created from a suggestion, it will always have an explicit
1011            // component here.
1012            getContext().startActivity(intent);
1013        } catch (RuntimeException ex) {
1014            Log.e(LOG_TAG, "Failed launch activity: " + intent, ex);
1015        }
1016    }
1017
1018    /**
1019     * Sets the text in the query box, without updating the suggestions.
1020     */
1021    private void setQuery(CharSequence query) {
1022        mQueryTextView.setText(query, true);
1023        // Move the cursor to the end
1024        mQueryTextView.setSelection(TextUtils.isEmpty(query) ? 0 : query.length());
1025    }
1026
1027    private void launchQuerySearch(int actionKey, String actionMsg, String query) {
1028        String action = Intent.ACTION_SEARCH;
1029        Intent intent = createIntent(action, null, null, query, actionKey, actionMsg);
1030        getContext().startActivity(intent);
1031    }
1032
1033    /**
1034     * Constructs an intent from the given information and the search dialog state.
1035     *
1036     * @param action Intent action.
1037     * @param data Intent data, or <code>null</code>.
1038     * @param extraData Data for {@link SearchManager#EXTRA_DATA_KEY} or <code>null</code>.
1039     * @param query Intent query, or <code>null</code>.
1040     * @param actionKey The key code of the action key that was pressed,
1041     *        or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
1042     * @param actionMsg The message for the action key that was pressed,
1043     *        or <code>null</code> if none.
1044     * @param mode The search mode, one of the acceptable values for
1045     *             {@link SearchManager#SEARCH_MODE}, or {@code null}.
1046     * @return The intent.
1047     */
1048    private Intent createIntent(String action, Uri data, String extraData, String query,
1049            int actionKey, String actionMsg) {
1050        // Now build the Intent
1051        Intent intent = new Intent(action);
1052        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1053        // We need CLEAR_TOP to avoid reusing an old task that has other activities
1054        // on top of the one we want. We don't want to do this in in-app search though,
1055        // as it can be destructive to the activity stack.
1056        if (data != null) {
1057            intent.setData(data);
1058        }
1059        intent.putExtra(SearchManager.USER_QUERY, query);
1060        if (query != null) {
1061            intent.putExtra(SearchManager.QUERY, query);
1062        }
1063        if (extraData != null) {
1064            intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
1065        }
1066        if (actionKey != KeyEvent.KEYCODE_UNKNOWN) {
1067            intent.putExtra(SearchManager.ACTION_KEY, actionKey);
1068            intent.putExtra(SearchManager.ACTION_MSG, actionMsg);
1069        }
1070        intent.setComponent(mSearchable.getSearchActivity());
1071        return intent;
1072    }
1073
1074    /**
1075     * Create and return an Intent that can launch the voice search activity for web search.
1076     */
1077    private Intent createVoiceWebSearchIntent(Intent baseIntent, SearchableInfo searchable) {
1078        Intent voiceIntent = new Intent(baseIntent);
1079        ComponentName searchActivity = searchable.getSearchActivity();
1080        voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null
1081                : searchActivity.flattenToShortString());
1082        return voiceIntent;
1083    }
1084
1085    /**
1086     * Create and return an Intent that can launch the voice search activity, perform a specific
1087     * voice transcription, and forward the results to the searchable activity.
1088     *
1089     * @param baseIntent The voice app search intent to start from
1090     * @return A completely-configured intent ready to send to the voice search activity
1091     */
1092    private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) {
1093        ComponentName searchActivity = searchable.getSearchActivity();
1094
1095        // create the necessary intent to set up a search-and-forward operation
1096        // in the voice search system.   We have to keep the bundle separate,
1097        // because it becomes immutable once it enters the PendingIntent
1098        Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
1099        queryIntent.setComponent(searchActivity);
1100        PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent,
1101                PendingIntent.FLAG_ONE_SHOT);
1102
1103        // Now set up the bundle that will be inserted into the pending intent
1104        // when it's time to do the search.  We always build it here (even if empty)
1105        // because the voice search activity will always need to insert "QUERY" into
1106        // it anyway.
1107        Bundle queryExtras = new Bundle();
1108
1109        // Now build the intent to launch the voice search.  Add all necessary
1110        // extras to launch the voice recognizer, and then all the necessary extras
1111        // to forward the results to the searchable activity
1112        Intent voiceIntent = new Intent(baseIntent);
1113
1114        // Add all of the configuration options supplied by the searchable's metadata
1115        String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM;
1116        String prompt = null;
1117        String language = null;
1118        int maxResults = 1;
1119
1120        Resources resources = getResources();
1121        if (searchable.getVoiceLanguageModeId() != 0) {
1122            languageModel = resources.getString(searchable.getVoiceLanguageModeId());
1123        }
1124        if (searchable.getVoicePromptTextId() != 0) {
1125            prompt = resources.getString(searchable.getVoicePromptTextId());
1126        }
1127        if (searchable.getVoiceLanguageId() != 0) {
1128            language = resources.getString(searchable.getVoiceLanguageId());
1129        }
1130        if (searchable.getVoiceMaxResults() != 0) {
1131            maxResults = searchable.getVoiceMaxResults();
1132        }
1133        voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel);
1134        voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
1135        voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
1136        voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
1137        voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null
1138                : searchActivity.flattenToShortString());
1139
1140        // Add the values that configure forwarding the results
1141        voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
1142        voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);
1143
1144        return voiceIntent;
1145    }
1146
1147    /**
1148     * When a particular suggestion has been selected, perform the various lookups required
1149     * to use the suggestion.  This includes checking the cursor for suggestion-specific data,
1150     * and/or falling back to the XML for defaults;  It also creates REST style Uri data when
1151     * the suggestion includes a data id.
1152     *
1153     * @param c The suggestions cursor, moved to the row of the user's selection
1154     * @param actionKey The key code of the action key that was pressed,
1155     *        or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
1156     * @param actionMsg The message for the action key that was pressed,
1157     *        or <code>null</code> if none.
1158     * @return An intent for the suggestion at the cursor's position.
1159     */
1160    private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) {
1161        try {
1162            // use specific action if supplied, or default action if supplied, or fixed default
1163            String action = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION);
1164
1165            if (action == null) {
1166                action = mSearchable.getSuggestIntentAction();
1167            }
1168            if (action == null) {
1169                action = Intent.ACTION_SEARCH;
1170            }
1171
1172            // use specific data if supplied, or default data if supplied
1173            String data = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA);
1174            if (data == null) {
1175                data = mSearchable.getSuggestIntentData();
1176            }
1177            // then, if an ID was provided, append it.
1178            if (data != null) {
1179                String id = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
1180                if (id != null) {
1181                    data = data + "/" + Uri.encode(id);
1182                }
1183            }
1184            Uri dataUri = (data == null) ? null : Uri.parse(data);
1185
1186            String query = getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY);
1187            String extraData = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
1188
1189            return createIntent(action, dataUri, extraData, query, actionKey, actionMsg);
1190        } catch (RuntimeException e ) {
1191            int rowNum;
1192            try {                       // be really paranoid now
1193                rowNum = c.getPosition();
1194            } catch (RuntimeException e2 ) {
1195                rowNum = -1;
1196            }
1197            Log.w(LOG_TAG, "Search Suggestions cursor at row " + rowNum +
1198                            " returned exception" + e.toString());
1199            return null;
1200        }
1201    }
1202
1203    static boolean isLandscapeMode(Context context) {
1204        return context.getResources().getConfiguration().orientation
1205                == Configuration.ORIENTATION_LANDSCAPE;
1206    }
1207
1208    /**
1209     * Callback to watch the text field for empty/non-empty
1210     */
1211    private TextWatcher mTextWatcher = new TextWatcher() {
1212
1213        public void beforeTextChanged(CharSequence s, int start, int before, int after) { }
1214
1215        public void onTextChanged(CharSequence s, int start,
1216                int before, int after) {
1217            SearchView.this.onTextChanged(s);
1218        }
1219
1220        public void afterTextChanged(Editable s) {
1221        }
1222    };
1223
1224    /**
1225     * Local subclass for AutoCompleteTextView.
1226     * @hide
1227     */
1228    public static class SearchAutoComplete extends AutoCompleteTextView {
1229
1230        private int mThreshold;
1231        private SearchView mSearchView;
1232
1233        public SearchAutoComplete(Context context) {
1234            super(context);
1235            mThreshold = getThreshold();
1236        }
1237
1238        public SearchAutoComplete(Context context, AttributeSet attrs) {
1239            super(context, attrs);
1240            mThreshold = getThreshold();
1241        }
1242
1243        public SearchAutoComplete(Context context, AttributeSet attrs, int defStyle) {
1244            super(context, attrs, defStyle);
1245            mThreshold = getThreshold();
1246        }
1247
1248        void setSearchView(SearchView searchView) {
1249            mSearchView = searchView;
1250        }
1251
1252        @Override
1253        public void setThreshold(int threshold) {
1254            super.setThreshold(threshold);
1255            mThreshold = threshold;
1256        }
1257
1258        /**
1259         * Returns true if the text field is empty, or contains only whitespace.
1260         */
1261        private boolean isEmpty() {
1262            return TextUtils.getTrimmedLength(getText()) == 0;
1263        }
1264
1265        /**
1266         * We override this method to avoid replacing the query box text when a
1267         * suggestion is clicked.
1268         */
1269        @Override
1270        protected void replaceText(CharSequence text) {
1271        }
1272
1273        /**
1274         * We override this method to avoid an extra onItemClick being called on
1275         * the drop-down's OnItemClickListener by
1276         * {@link AutoCompleteTextView#onKeyUp(int, KeyEvent)} when an item is
1277         * clicked with the trackball.
1278         */
1279        @Override
1280        public void performCompletion() {
1281        }
1282
1283        /**
1284         * We override this method to be sure and show the soft keyboard if
1285         * appropriate when the TextView has focus.
1286         */
1287        @Override
1288        public void onWindowFocusChanged(boolean hasWindowFocus) {
1289            super.onWindowFocusChanged(hasWindowFocus);
1290
1291            if (hasWindowFocus && mSearchView.hasFocus() && getVisibility() == VISIBLE) {
1292                InputMethodManager inputManager = (InputMethodManager) getContext()
1293                        .getSystemService(Context.INPUT_METHOD_SERVICE);
1294                inputManager.showSoftInput(this, 0);
1295                // If in landscape mode, then make sure that
1296                // the ime is in front of the dropdown.
1297                if (isLandscapeMode(getContext())) {
1298                    ensureImeVisible(true);
1299                }
1300            }
1301        }
1302
1303        @Override
1304        protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
1305            super.onFocusChanged(focused, direction, previouslyFocusedRect);
1306            mSearchView.onTextFocusChanged();
1307        }
1308
1309        /**
1310         * We override this method so that we can allow a threshold of zero,
1311         * which ACTV does not.
1312         */
1313        @Override
1314        public boolean enoughToFilter() {
1315            return mThreshold <= 0 || super.enoughToFilter();
1316        }
1317    }
1318}
1319