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