blob: 1eedc5d7b6c98dc5eaf9fdcfcc4f8b9f1a6eb3f8 [file] [log] [blame]
Amith Yamasani733cbd52010-09-03 12:21:39 -07001/*
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
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -070021import android.app.PendingIntent;
Amith Yamasani733cbd52010-09-03 12:21:39 -070022import android.app.SearchManager;
23import android.app.SearchableInfo;
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -070024import android.content.ActivityNotFoundException;
25import android.content.ComponentName;
Amith Yamasani733cbd52010-09-03 12:21:39 -070026import android.content.Context;
27import android.content.Intent;
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -070028import android.content.pm.PackageManager;
29import android.content.pm.ResolveInfo;
Amith Yamasani968ec932010-12-02 14:00:47 -080030import android.content.res.Configuration;
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -070031import android.content.res.Resources;
Amith Yamasani733cbd52010-09-03 12:21:39 -070032import android.content.res.TypedArray;
33import android.database.Cursor;
repo sync6a81b822010-09-28 13:00:05 -070034import android.graphics.Rect;
Amith Yamasani733cbd52010-09-03 12:21:39 -070035import android.graphics.drawable.Drawable;
36import android.net.Uri;
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -070037import android.os.Bundle;
38import android.speech.RecognizerIntent;
Amith Yamasani733cbd52010-09-03 12:21:39 -070039import android.text.Editable;
Amith Yamasani5607a382011-08-09 14:16:37 -070040import android.text.InputType;
Amith Yamasanib4569fb2011-07-08 15:25:39 -070041import android.text.Spannable;
42import android.text.SpannableStringBuilder;
Amith Yamasani733cbd52010-09-03 12:21:39 -070043import android.text.TextUtils;
44import android.text.TextWatcher;
Amith Yamasanib4569fb2011-07-08 15:25:39 -070045import android.text.style.ImageSpan;
Amith Yamasani733cbd52010-09-03 12:21:39 -070046import android.util.AttributeSet;
47import android.util.Log;
Amith Yamasanib4569fb2011-07-08 15:25:39 -070048import android.util.TypedValue;
Amith Yamasani763bc072011-07-22 11:53:47 -070049import android.view.CollapsibleActionView;
Amith Yamasani733cbd52010-09-03 12:21:39 -070050import android.view.KeyEvent;
51import android.view.LayoutInflater;
52import android.view.View;
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -080053import android.view.accessibility.AccessibilityEvent;
54import android.view.accessibility.AccessibilityNodeInfo;
Amith Yamasani5607a382011-08-09 14:16:37 -070055import android.view.inputmethod.EditorInfo;
Amith Yamasani733cbd52010-09-03 12:21:39 -070056import android.view.inputmethod.InputMethodManager;
57import android.widget.AdapterView.OnItemClickListener;
58import android.widget.AdapterView.OnItemSelectedListener;
59import android.widget.TextView.OnEditorActionListener;
60
Amith Yamasanib4569fb2011-07-08 15:25:39 -070061import com.android.internal.R;
62
Amith Yamasani733cbd52010-09-03 12:21:39 -070063import java.util.WeakHashMap;
64
65/**
Amith Yamasani763bc072011-07-22 11:53:47 -070066 * A widget that provides a user interface for the user to enter a search query and submit a request
67 * to a search provider. Shows a list of query suggestions or results, if available, and allows the
68 * user to pick a suggestion or result to launch into.
Amith Yamasani5931b1f2010-10-18 16:13:14 -070069 *
Amith Yamasani763bc072011-07-22 11:53:47 -070070 * <p>
71 * When the SearchView is used in an ActionBar as an action view for a collapsible menu item, it
72 * needs to be set to iconified by default using {@link #setIconifiedByDefault(boolean)
73 * setIconifiedByDefault(true)}. This is the default, so nothing needs to be done.
74 * </p>
75 * <p>
76 * If you want the search field to always be visible, then call setIconifiedByDefault(false).
77 * </p>
Amith Yamasani5931b1f2010-10-18 16:13:14 -070078 *
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080079 * <div class="special reference">
80 * <h3>Developer Guides</h3>
81 * <p>For information about using {@code SearchView}, read the
82 * <a href="{@docRoot}guide/topics/search/index.html">Search</a> developer guide.</p>
83 * </div>
Amith Yamasani763bc072011-07-22 11:53:47 -070084 *
85 * @see android.view.MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
Amith Yamasani5931b1f2010-10-18 16:13:14 -070086 * @attr ref android.R.styleable#SearchView_iconifiedByDefault
Amith Yamasani5607a382011-08-09 14:16:37 -070087 * @attr ref android.R.styleable#SearchView_imeOptions
88 * @attr ref android.R.styleable#SearchView_inputType
Amith Yamasani5931b1f2010-10-18 16:13:14 -070089 * @attr ref android.R.styleable#SearchView_maxWidth
Scott Mainabdf0d52011-02-08 10:20:27 -080090 * @attr ref android.R.styleable#SearchView_queryHint
Amith Yamasani733cbd52010-09-03 12:21:39 -070091 */
Amith Yamasani763bc072011-07-22 11:53:47 -070092public class SearchView extends LinearLayout implements CollapsibleActionView {
Amith Yamasani733cbd52010-09-03 12:21:39 -070093
94 private static final boolean DBG = false;
95 private static final String LOG_TAG = "SearchView";
96
Luca Zanolin535698c2011-10-06 13:36:15 +010097 /**
98 * Private constant for removing the microphone in the keyboard.
99 */
100 private static final String IME_OPTION_NO_MICROPHONE = "nm";
101
Adam Powell01f21352011-01-20 18:30:10 -0800102 private OnQueryTextListener mOnQueryChangeListener;
Amith Yamasani733cbd52010-09-03 12:21:39 -0700103 private OnCloseListener mOnCloseListener;
Amith Yamasani05944762010-10-08 13:52:38 -0700104 private OnFocusChangeListener mOnQueryTextFocusChangeListener;
Adam Powell01f21352011-01-20 18:30:10 -0800105 private OnSuggestionListener mOnSuggestionListener;
Amith Yamasani48385482010-12-03 14:43:52 -0800106 private OnClickListener mOnSearchClickListener;
Amith Yamasani733cbd52010-09-03 12:21:39 -0700107
108 private boolean mIconifiedByDefault;
Amith Yamasani93227752010-09-14 10:10:54 -0700109 private boolean mIconified;
Amith Yamasani733cbd52010-09-03 12:21:39 -0700110 private CursorAdapter mSuggestionsAdapter;
111 private View mSearchButton;
112 private View mSubmitButton;
Amith Yamasani79f74302011-03-08 14:16:35 -0800113 private View mSearchPlate;
Amith Yamasani9b2e3022011-01-14 11:34:12 -0800114 private View mSubmitArea;
Amith Yamasani4aedb392010-12-15 16:04:57 -0800115 private ImageView mCloseButton;
Amith Yamasani733cbd52010-09-03 12:21:39 -0700116 private View mSearchEditFrame;
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -0700117 private View mVoiceButton;
Amith Yamasani968ec932010-12-02 14:00:47 -0800118 private SearchAutoComplete mQueryTextView;
Amith Yamasanib4569fb2011-07-08 15:25:39 -0700119 private View mDropDownAnchor;
120 private ImageView mSearchHintIcon;
Amith Yamasani733cbd52010-09-03 12:21:39 -0700121 private boolean mSubmitButtonEnabled;
122 private CharSequence mQueryHint;
Amith Yamasanie678f462010-09-15 16:13:43 -0700123 private boolean mQueryRefinement;
Amith Yamasani05944762010-10-08 13:52:38 -0700124 private boolean mClearingFocus;
Amith Yamasani5931b1f2010-10-18 16:13:14 -0700125 private int mMaxWidth;
Amith Yamasani9b2e3022011-01-14 11:34:12 -0800126 private boolean mVoiceButtonEnabled;
Amith Yamasanib47c4fd2011-08-04 14:30:07 -0700127 private CharSequence mOldQueryText;
Amith Yamasani068d73c2011-05-27 15:15:14 -0700128 private CharSequence mUserQuery;
Amith Yamasani763bc072011-07-22 11:53:47 -0700129 private boolean mExpandedInActionView;
Adam Powell53f56c42011-09-25 13:46:15 -0700130 private int mCollapsedImeOptions;
Amith Yamasani733cbd52010-09-03 12:21:39 -0700131
132 private SearchableInfo mSearchable;
Amith Yamasani940ef382011-03-02 18:43:23 -0800133 private Bundle mAppSearchData;
Amith Yamasani733cbd52010-09-03 12:21:39 -0700134
Adam Powellccdd4ee2011-07-27 20:05:14 -0700135 /*
136 * SearchView can be set expanded before the IME is ready to be shown during
137 * initial UI setup. The show operation is asynchronous to account for this.
138 */
139 private Runnable mShowImeRunnable = new Runnable() {
140 public void run() {
141 InputMethodManager imm = (InputMethodManager)
142 getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
143
144 if (imm != null) {
145 imm.showSoftInputUnchecked(0, null);
146 }
147 }
148 };
149
Amith Yamasania95e4882011-08-17 11:41:37 -0700150 private Runnable mUpdateDrawableStateRunnable = new Runnable() {
151 public void run() {
152 updateFocusedState();
153 }
154 };
155
Amith Yamasani87907642011-11-03 11:32:44 -0700156 private Runnable mReleaseCursorRunnable = new Runnable() {
157 public void run() {
158 if (mSuggestionsAdapter != null && mSuggestionsAdapter instanceof SuggestionsAdapter) {
159 mSuggestionsAdapter.changeCursor(null);
160 }
161 }
162 };
163
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -0700164 // For voice searching
165 private final Intent mVoiceWebSearchIntent;
166 private final Intent mVoiceAppSearchIntent;
167
Amith Yamasani733cbd52010-09-03 12:21:39 -0700168 // A weak map of drawables we've gotten from other packages, so we don't load them
169 // more than once.
170 private final WeakHashMap<String, Drawable.ConstantState> mOutsideDrawablesCache =
171 new WeakHashMap<String, Drawable.ConstantState>();
172
173 /**
174 * Callbacks for changes to the query text.
175 */
Adam Powell01f21352011-01-20 18:30:10 -0800176 public interface OnQueryTextListener {
Amith Yamasani733cbd52010-09-03 12:21:39 -0700177
178 /**
179 * Called when the user submits the query. This could be due to a key press on the
180 * keyboard or due to pressing a submit button.
181 * The listener can override the standard behavior by returning true
182 * to indicate that it has handled the submit request. Otherwise return false to
183 * let the SearchView handle the submission by launching any associated intent.
184 *
185 * @param query the query text that is to be submitted
186 *
187 * @return true if the query has been handled by the listener, false to let the
188 * SearchView perform the default action.
189 */
Adam Powell01f21352011-01-20 18:30:10 -0800190 boolean onQueryTextSubmit(String query);
Amith Yamasani733cbd52010-09-03 12:21:39 -0700191
192 /**
193 * Called when the query text is changed by the user.
194 *
195 * @param newText the new content of the query text field.
196 *
197 * @return false if the SearchView should perform the default action of showing any
198 * suggestions if available, true if the action was handled by the listener.
199 */
Adam Powell01f21352011-01-20 18:30:10 -0800200 boolean onQueryTextChange(String newText);
Amith Yamasani733cbd52010-09-03 12:21:39 -0700201 }
202
203 public interface OnCloseListener {
204
205 /**
206 * The user is attempting to close the SearchView.
207 *
208 * @return true if the listener wants to override the default behavior of clearing the
209 * text field and dismissing it, false otherwise.
210 */
211 boolean onClose();
212 }
213
Amith Yamasani05944762010-10-08 13:52:38 -0700214 /**
215 * Callback interface for selection events on suggestions. These callbacks
216 * are only relevant when a SearchableInfo has been specified by {@link #setSearchableInfo}.
217 */
Adam Powell01f21352011-01-20 18:30:10 -0800218 public interface OnSuggestionListener {
Amith Yamasani05944762010-10-08 13:52:38 -0700219
220 /**
221 * Called when a suggestion was selected by navigating to it.
222 * @param position the absolute position in the list of suggestions.
223 *
224 * @return true if the listener handles the event and wants to override the default
225 * behavior of possibly rewriting the query based on the selected item, false otherwise.
226 */
Adam Powell01f21352011-01-20 18:30:10 -0800227 boolean onSuggestionSelect(int position);
Amith Yamasani05944762010-10-08 13:52:38 -0700228
229 /**
230 * Called when a suggestion was clicked.
231 * @param position the absolute position of the clicked item in the list of suggestions.
232 *
233 * @return true if the listener handles the event and wants to override the default
234 * behavior of launching any intent or submitting a search query specified on that item.
235 * Return false otherwise.
236 */
Adam Powell01f21352011-01-20 18:30:10 -0800237 boolean onSuggestionClick(int position);
Amith Yamasani05944762010-10-08 13:52:38 -0700238 }
239
Amith Yamasani733cbd52010-09-03 12:21:39 -0700240 public SearchView(Context context) {
241 this(context, null);
242 }
243
244 public SearchView(Context context, AttributeSet attrs) {
Alan Viverette617feb92013-09-09 18:09:13 -0700245 this(context, attrs, 0);
246 }
247
248 public SearchView(Context context, AttributeSet attrs, int defStyleAttr) {
249 this(context, attrs, defStyleAttr, 0);
250 }
251
252 public SearchView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
253 super(context, attrs, defStyleAttr, defStyleRes);
Amith Yamasani733cbd52010-09-03 12:21:39 -0700254
255 LayoutInflater inflater = (LayoutInflater) context
256 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
257 inflater.inflate(R.layout.search_view, this, true);
258
259 mSearchButton = findViewById(R.id.search_button);
Amith Yamasani968ec932010-12-02 14:00:47 -0800260 mQueryTextView = (SearchAutoComplete) findViewById(R.id.search_src_text);
261 mQueryTextView.setSearchView(this);
262
Amith Yamasani733cbd52010-09-03 12:21:39 -0700263 mSearchEditFrame = findViewById(R.id.search_edit_frame);
Amith Yamasani79f74302011-03-08 14:16:35 -0800264 mSearchPlate = findViewById(R.id.search_plate);
Amith Yamasani9b2e3022011-01-14 11:34:12 -0800265 mSubmitArea = findViewById(R.id.submit_area);
Amith Yamasani733cbd52010-09-03 12:21:39 -0700266 mSubmitButton = findViewById(R.id.search_go_btn);
Amith Yamasani4aedb392010-12-15 16:04:57 -0800267 mCloseButton = (ImageView) findViewById(R.id.search_close_btn);
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -0700268 mVoiceButton = findViewById(R.id.search_voice_btn);
Amith Yamasanib4569fb2011-07-08 15:25:39 -0700269 mSearchHintIcon = (ImageView) findViewById(R.id.search_mag_icon);
Amith Yamasani733cbd52010-09-03 12:21:39 -0700270
271 mSearchButton.setOnClickListener(mOnClickListener);
272 mCloseButton.setOnClickListener(mOnClickListener);
273 mSubmitButton.setOnClickListener(mOnClickListener);
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -0700274 mVoiceButton.setOnClickListener(mOnClickListener);
Amith Yamasanif28d1872011-07-26 12:21:03 -0700275 mQueryTextView.setOnClickListener(mOnClickListener);
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -0700276
Amith Yamasani733cbd52010-09-03 12:21:39 -0700277 mQueryTextView.addTextChangedListener(mTextWatcher);
278 mQueryTextView.setOnEditorActionListener(mOnEditorActionListener);
279 mQueryTextView.setOnItemClickListener(mOnItemClickListener);
280 mQueryTextView.setOnItemSelectedListener(mOnItemSelectedListener);
Amith Yamasani968ec932010-12-02 14:00:47 -0800281 mQueryTextView.setOnKeyListener(mTextKeyListener);
Luca Zanolin535698c2011-10-06 13:36:15 +0100282 // Inform any listener of focus changes
Amith Yamasani05944762010-10-08 13:52:38 -0700283 mQueryTextView.setOnFocusChangeListener(new OnFocusChangeListener() {
284
285 public void onFocusChange(View v, boolean hasFocus) {
286 if (mOnQueryTextFocusChangeListener != null) {
287 mOnQueryTextFocusChangeListener.onFocusChange(SearchView.this, hasFocus);
288 }
289 }
290 });
Amith Yamasani733cbd52010-09-03 12:21:39 -0700291
Alan Viverette617feb92013-09-09 18:09:13 -0700292 TypedArray a = context.obtainStyledAttributes(
293 attrs, R.styleable.SearchView, defStyleAttr, defStyleRes);
Amith Yamasani733cbd52010-09-03 12:21:39 -0700294 setIconifiedByDefault(a.getBoolean(R.styleable.SearchView_iconifiedByDefault, true));
Amith Yamasani5931b1f2010-10-18 16:13:14 -0700295 int maxWidth = a.getDimensionPixelSize(R.styleable.SearchView_maxWidth, -1);
296 if (maxWidth != -1) {
297 setMaxWidth(maxWidth);
298 }
Adam Powellc0171d52011-01-13 14:31:17 -0800299 CharSequence queryHint = a.getText(R.styleable.SearchView_queryHint);
300 if (!TextUtils.isEmpty(queryHint)) {
301 setQueryHint(queryHint);
302 }
Amith Yamasani5607a382011-08-09 14:16:37 -0700303 int imeOptions = a.getInt(R.styleable.SearchView_imeOptions, -1);
304 if (imeOptions != -1) {
305 setImeOptions(imeOptions);
306 }
307 int inputType = a.getInt(R.styleable.SearchView_inputType, -1);
308 if (inputType != -1) {
309 setInputType(inputType);
310 }
311
Amith Yamasani733cbd52010-09-03 12:21:39 -0700312 a.recycle();
313
Amith Yamasani5607a382011-08-09 14:16:37 -0700314 boolean focusable = true;
315
Alan Viverette617feb92013-09-09 18:09:13 -0700316 a = context.obtainStyledAttributes(attrs, R.styleable.View, defStyleAttr, defStyleRes);
Amith Yamasani7f8aef62011-01-25 11:58:09 -0800317 focusable = a.getBoolean(R.styleable.View_focusable, focusable);
318 a.recycle();
319 setFocusable(focusable);
320
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -0700321 // Save voice intent for later queries/launching
322 mVoiceWebSearchIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
323 mVoiceWebSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
324 mVoiceWebSearchIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
325 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
326
327 mVoiceAppSearchIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
328 mVoiceAppSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
329
Amith Yamasanib4569fb2011-07-08 15:25:39 -0700330 mDropDownAnchor = findViewById(mQueryTextView.getDropDownAnchor());
331 if (mDropDownAnchor != null) {
332 mDropDownAnchor.addOnLayoutChangeListener(new OnLayoutChangeListener() {
333 @Override
334 public void onLayoutChange(View v, int left, int top, int right, int bottom,
335 int oldLeft, int oldTop, int oldRight, int oldBottom) {
336 adjustDropDownSizeAndPosition();
337 }
Amith Yamasanib4569fb2011-07-08 15:25:39 -0700338 });
339 }
340
Amith Yamasani733cbd52010-09-03 12:21:39 -0700341 updateViewsVisibility(mIconifiedByDefault);
Amith Yamasanib4569fb2011-07-08 15:25:39 -0700342 updateQueryHint();
Amith Yamasani733cbd52010-09-03 12:21:39 -0700343 }
344
345 /**
346 * Sets the SearchableInfo for this SearchView. Properties in the SearchableInfo are used
347 * to display labels, hints, suggestions, create intents for launching search results screens
348 * and controlling other affordances such as a voice button.
349 *
350 * @param searchable a SearchableInfo can be retrieved from the SearchManager, for a specific
351 * activity or a global search provider.
352 */
353 public void setSearchableInfo(SearchableInfo searchable) {
354 mSearchable = searchable;
355 if (mSearchable != null) {
356 updateSearchAutoComplete();
Amith Yamasani79f74302011-03-08 14:16:35 -0800357 updateQueryHint();
Amith Yamasani733cbd52010-09-03 12:21:39 -0700358 }
Amith Yamasani9b2e3022011-01-14 11:34:12 -0800359 // Cache the voice search capability
360 mVoiceButtonEnabled = hasVoiceSearch();
Luca Zanolin535698c2011-10-06 13:36:15 +0100361
362 if (mVoiceButtonEnabled) {
363 // Disable the microphone on the keyboard, as a mic is displayed near the text box
364 // TODO: use imeOptions to disable voice input when the new API will be available
365 mQueryTextView.setPrivateImeOptions(IME_OPTION_NO_MICROPHONE);
366 }
Amith Yamasanib4569fb2011-07-08 15:25:39 -0700367 updateViewsVisibility(isIconified());
Amith Yamasani733cbd52010-09-03 12:21:39 -0700368 }
369
Amith Yamasani940ef382011-03-02 18:43:23 -0800370 /**
371 * Sets the APP_DATA for legacy SearchDialog use.
372 * @param appSearchData bundle provided by the app when launching the search dialog
373 * @hide
374 */
375 public void setAppSearchData(Bundle appSearchData) {
376 mAppSearchData = appSearchData;
377 }
378
Amith Yamasani5607a382011-08-09 14:16:37 -0700379 /**
380 * Sets the IME options on the query text field.
381 *
382 * @see TextView#setImeOptions(int)
383 * @param imeOptions the options to set on the query text field
384 *
385 * @attr ref android.R.styleable#SearchView_imeOptions
386 */
387 public void setImeOptions(int imeOptions) {
388 mQueryTextView.setImeOptions(imeOptions);
389 }
390
391 /**
Amith Yamasanieca59d32012-04-25 18:57:18 -0700392 * Returns the IME options set on the query text field.
393 * @return the ime options
394 * @see TextView#setImeOptions(int)
395 *
396 * @attr ref android.R.styleable#SearchView_imeOptions
397 */
398 public int getImeOptions() {
399 return mQueryTextView.getImeOptions();
400 }
401
402 /**
Amith Yamasani5607a382011-08-09 14:16:37 -0700403 * Sets the input type on the query text field.
404 *
405 * @see TextView#setInputType(int)
406 * @param inputType the input type to set on the query text field
407 *
408 * @attr ref android.R.styleable#SearchView_inputType
409 */
410 public void setInputType(int inputType) {
411 mQueryTextView.setInputType(inputType);
412 }
413
Amith Yamasanieca59d32012-04-25 18:57:18 -0700414 /**
415 * Returns the input type set on the query text field.
416 * @return the input type
417 *
418 * @attr ref android.R.styleable#SearchView_inputType
419 */
420 public int getInputType() {
421 return mQueryTextView.getInputType();
422 }
423
Amith Yamasani05944762010-10-08 13:52:38 -0700424 /** @hide */
425 @Override
426 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
Amith Yamasani7f8aef62011-01-25 11:58:09 -0800427 // Don't accept focus if in the middle of clearing focus
428 if (mClearingFocus) return false;
429 // Check if SearchView is focusable.
430 if (!isFocusable()) return false;
431 // If it is not iconified, then give the focus to the text field
432 if (!isIconified()) {
433 boolean result = mQueryTextView.requestFocus(direction, previouslyFocusedRect);
Amith Yamasanif28d1872011-07-26 12:21:03 -0700434 if (result) {
435 updateViewsVisibility(false);
436 }
Amith Yamasani7f8aef62011-01-25 11:58:09 -0800437 return result;
438 } else {
439 return super.requestFocus(direction, previouslyFocusedRect);
440 }
Amith Yamasani05944762010-10-08 13:52:38 -0700441 }
442
443 /** @hide */
444 @Override
445 public void clearFocus() {
446 mClearingFocus = true;
Amith Yamasani10da5902011-07-26 16:14:26 -0700447 setImeVisibility(false);
Amith Yamasani05944762010-10-08 13:52:38 -0700448 super.clearFocus();
449 mQueryTextView.clearFocus();
Amith Yamasani05944762010-10-08 13:52:38 -0700450 mClearingFocus = false;
451 }
452
Amith Yamasani733cbd52010-09-03 12:21:39 -0700453 /**
454 * Sets a listener for user actions within the SearchView.
455 *
456 * @param listener the listener object that receives callbacks when the user performs
457 * actions in the SearchView such as clicking on buttons or typing a query.
458 */
Adam Powell01f21352011-01-20 18:30:10 -0800459 public void setOnQueryTextListener(OnQueryTextListener listener) {
Amith Yamasani733cbd52010-09-03 12:21:39 -0700460 mOnQueryChangeListener = listener;
461 }
462
463 /**
Amith Yamasani93227752010-09-14 10:10:54 -0700464 * Sets a listener to inform when the user closes the SearchView.
465 *
466 * @param listener the listener to call when the user closes the SearchView.
467 */
468 public void setOnCloseListener(OnCloseListener listener) {
469 mOnCloseListener = listener;
470 }
471
472 /**
Amith Yamasani05944762010-10-08 13:52:38 -0700473 * Sets a listener to inform when the focus of the query text field changes.
474 *
475 * @param listener the listener to inform of focus changes.
476 */
477 public void setOnQueryTextFocusChangeListener(OnFocusChangeListener listener) {
478 mOnQueryTextFocusChangeListener = listener;
479 }
480
481 /**
482 * Sets a listener to inform when a suggestion is focused or clicked.
483 *
484 * @param listener the listener to inform of suggestion selection events.
485 */
Adam Powell01f21352011-01-20 18:30:10 -0800486 public void setOnSuggestionListener(OnSuggestionListener listener) {
Amith Yamasani05944762010-10-08 13:52:38 -0700487 mOnSuggestionListener = listener;
488 }
489
490 /**
Amith Yamasani48385482010-12-03 14:43:52 -0800491 * Sets a listener to inform when the search button is pressed. This is only
Scott Maincccdbe92011-02-06 15:51:47 -0800492 * relevant when the text field is not visible by default. Calling {@link #setIconified
493 * setIconified(false)} can also cause this listener to be informed.
Amith Yamasani48385482010-12-03 14:43:52 -0800494 *
495 * @param listener the listener to inform when the search button is clicked or
496 * the text field is programmatically de-iconified.
497 */
498 public void setOnSearchClickListener(OnClickListener listener) {
499 mOnSearchClickListener = listener;
500 }
501
502 /**
503 * Returns the query string currently in the text field.
504 *
505 * @return the query string
506 */
507 public CharSequence getQuery() {
508 return mQueryTextView.getText();
509 }
510
511 /**
Amith Yamasani733cbd52010-09-03 12:21:39 -0700512 * Sets a query string in the text field and optionally submits the query as well.
513 *
514 * @param query the query string. This replaces any query text already present in the
515 * text field.
516 * @param submit whether to submit the query right now or only update the contents of
517 * text field.
518 */
519 public void setQuery(CharSequence query, boolean submit) {
520 mQueryTextView.setText(query);
Dmitri Plotnikov87c50252010-10-21 21:16:42 -0700521 if (query != null) {
Gilles Debunne24271922012-05-25 14:04:01 +0200522 mQueryTextView.setSelection(mQueryTextView.length());
Amith Yamasani068d73c2011-05-27 15:15:14 -0700523 mUserQuery = query;
Dmitri Plotnikov87c50252010-10-21 21:16:42 -0700524 }
525
Amith Yamasani733cbd52010-09-03 12:21:39 -0700526 // If the query is not empty and submit is requested, submit the query
527 if (submit && !TextUtils.isEmpty(query)) {
528 onSubmitQuery();
529 }
530 }
531
532 /**
533 * Sets the hint text to display in the query text field. This overrides any hint specified
534 * in the SearchableInfo.
535 *
536 * @param hint the hint text to display
Scott Mainabdf0d52011-02-08 10:20:27 -0800537 *
538 * @attr ref android.R.styleable#SearchView_queryHint
Amith Yamasani733cbd52010-09-03 12:21:39 -0700539 */
540 public void setQueryHint(CharSequence hint) {
541 mQueryHint = hint;
542 updateQueryHint();
543 }
544
545 /**
Amith Yamasanieca59d32012-04-25 18:57:18 -0700546 * Gets the hint text to display in the query text field.
547 * @return the query hint text, if specified, null otherwise.
548 *
549 * @attr ref android.R.styleable#SearchView_queryHint
550 */
551 public CharSequence getQueryHint() {
552 if (mQueryHint != null) {
553 return mQueryHint;
554 } else if (mSearchable != null) {
555 CharSequence hint = null;
556 int hintId = mSearchable.getHintId();
557 if (hintId != 0) {
558 hint = getContext().getString(hintId);
559 }
560 return hint;
561 }
562 return null;
563 }
564
565 /**
Amith Yamasani733cbd52010-09-03 12:21:39 -0700566 * Sets the default or resting state of the search field. If true, a single search icon is
567 * shown by default and expands to show the text field and other buttons when pressed. Also,
568 * if the default state is iconified, then it collapses to that state when the close button
Amith Yamasani93227752010-09-14 10:10:54 -0700569 * is pressed. Changes to this property will take effect immediately.
Amith Yamasani733cbd52010-09-03 12:21:39 -0700570 *
Scott Maincccdbe92011-02-06 15:51:47 -0800571 * <p>The default value is true.</p>
Amith Yamasani93227752010-09-14 10:10:54 -0700572 *
573 * @param iconified whether the search field should be iconified by default
Scott Mainabdf0d52011-02-08 10:20:27 -0800574 *
575 * @attr ref android.R.styleable#SearchView_iconifiedByDefault
Amith Yamasani733cbd52010-09-03 12:21:39 -0700576 */
577 public void setIconifiedByDefault(boolean iconified) {
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -0700578 if (mIconifiedByDefault == iconified) return;
Amith Yamasani733cbd52010-09-03 12:21:39 -0700579 mIconifiedByDefault = iconified;
580 updateViewsVisibility(iconified);
Amith Yamasanib47c4fd2011-08-04 14:30:07 -0700581 updateQueryHint();
Amith Yamasani733cbd52010-09-03 12:21:39 -0700582 }
583
Amith Yamasani93227752010-09-14 10:10:54 -0700584 /**
585 * Returns the default iconified state of the search field.
586 * @return
Amith Yamasani3d3e7a52012-05-04 14:46:31 -0700587 *
588 * @attr ref android.R.styleable#SearchView_iconifiedByDefault
Amith Yamasani93227752010-09-14 10:10:54 -0700589 */
Amith Yamasani733cbd52010-09-03 12:21:39 -0700590 public boolean isIconfiedByDefault() {
591 return mIconifiedByDefault;
592 }
593
594 /**
Amith Yamasani93227752010-09-14 10:10:54 -0700595 * Iconifies or expands the SearchView. Any query text is cleared when iconified. This is
596 * a temporary state and does not override the default iconified state set by
597 * {@link #setIconifiedByDefault(boolean)}. If the default state is iconified, then
598 * a false here will only be valid until the user closes the field. And if the default
599 * state is expanded, then a true here will only clear the text field and not close it.
600 *
601 * @param iconify a true value will collapse the SearchView to an icon, while a false will
602 * expand it.
603 */
604 public void setIconified(boolean iconify) {
605 if (iconify) {
606 onCloseClicked();
607 } else {
608 onSearchClicked();
609 }
610 }
611
612 /**
613 * Returns the current iconified state of the SearchView.
614 *
615 * @return true if the SearchView is currently iconified, false if the search field is
616 * fully visible.
617 */
618 public boolean isIconified() {
619 return mIconified;
620 }
621
622 /**
Amith Yamasani733cbd52010-09-03 12:21:39 -0700623 * Enables showing a submit button when the query is non-empty. In cases where the SearchView
624 * is being used to filter the contents of the current activity and doesn't launch a separate
625 * results activity, then the submit button should be disabled.
626 *
627 * @param enabled true to show a submit button for submitting queries, false if a submit
628 * button is not required.
629 */
630 public void setSubmitButtonEnabled(boolean enabled) {
Amith Yamasani733cbd52010-09-03 12:21:39 -0700631 mSubmitButtonEnabled = enabled;
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -0700632 updateViewsVisibility(isIconified());
Amith Yamasani733cbd52010-09-03 12:21:39 -0700633 }
634
635 /**
636 * Returns whether the submit button is enabled when necessary or never displayed.
637 *
638 * @return whether the submit button is enabled automatically when necessary
639 */
640 public boolean isSubmitButtonEnabled() {
641 return mSubmitButtonEnabled;
642 }
643
Amith Yamasanie678f462010-09-15 16:13:43 -0700644 /**
645 * Specifies if a query refinement button should be displayed alongside each suggestion
646 * or if it should depend on the flags set in the individual items retrieved from the
647 * suggestions provider. Clicking on the query refinement button will replace the text
648 * in the query text field with the text from the suggestion. This flag only takes effect
649 * if a SearchableInfo has been specified with {@link #setSearchableInfo(SearchableInfo)}
650 * and not when using a custom adapter.
651 *
652 * @param enable true if all items should have a query refinement button, false if only
653 * those items that have a query refinement flag set should have the button.
654 *
655 * @see SearchManager#SUGGEST_COLUMN_FLAGS
656 * @see SearchManager#FLAG_QUERY_REFINEMENT
657 */
658 public void setQueryRefinementEnabled(boolean enable) {
659 mQueryRefinement = enable;
660 if (mSuggestionsAdapter instanceof SuggestionsAdapter) {
661 ((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement(
662 enable ? SuggestionsAdapter.REFINE_ALL : SuggestionsAdapter.REFINE_BY_ENTRY);
663 }
664 }
665
666 /**
667 * Returns whether query refinement is enabled for all items or only specific ones.
668 * @return true if enabled for all items, false otherwise.
669 */
670 public boolean isQueryRefinementEnabled() {
671 return mQueryRefinement;
Amith Yamasani733cbd52010-09-03 12:21:39 -0700672 }
673
674 /**
675 * You can set a custom adapter if you wish. Otherwise the default adapter is used to
676 * display the suggestions from the suggestions provider associated with the SearchableInfo.
677 *
678 * @see #setSearchableInfo(SearchableInfo)
679 */
680 public void setSuggestionsAdapter(CursorAdapter adapter) {
681 mSuggestionsAdapter = adapter;
682
683 mQueryTextView.setAdapter(mSuggestionsAdapter);
684 }
685
686 /**
687 * Returns the adapter used for suggestions, if any.
688 * @return the suggestions adapter
689 */
690 public CursorAdapter getSuggestionsAdapter() {
691 return mSuggestionsAdapter;
692 }
693
Amith Yamasani5931b1f2010-10-18 16:13:14 -0700694 /**
695 * Makes the view at most this many pixels wide
696 *
697 * @attr ref android.R.styleable#SearchView_maxWidth
698 */
699 public void setMaxWidth(int maxpixels) {
700 mMaxWidth = maxpixels;
701
702 requestLayout();
703 }
704
Amith Yamasanieca59d32012-04-25 18:57:18 -0700705 /**
706 * Gets the specified maximum width in pixels, if set. Returns zero if
707 * no maximum width was specified.
708 * @return the maximum width of the view
Amith Yamasani3d3e7a52012-05-04 14:46:31 -0700709 *
710 * @attr ref android.R.styleable#SearchView_maxWidth
Amith Yamasanieca59d32012-04-25 18:57:18 -0700711 */
712 public int getMaxWidth() {
713 return mMaxWidth;
714 }
715
Amith Yamasani5931b1f2010-10-18 16:13:14 -0700716 @Override
717 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Amith Yamasania95e4882011-08-17 11:41:37 -0700718 // Let the standard measurements take effect in iconified state.
719 if (isIconified()) {
720 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
721 return;
722 }
723
Amith Yamasani5931b1f2010-10-18 16:13:14 -0700724 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
725 int width = MeasureSpec.getSize(widthMeasureSpec);
726
Amith Yamasani167d69a2011-08-12 19:28:37 -0700727 switch (widthMode) {
728 case MeasureSpec.AT_MOST:
729 // If there is an upper limit, don't exceed maximum width (explicit or implicit)
730 if (mMaxWidth > 0) {
731 width = Math.min(mMaxWidth, width);
732 } else {
733 width = Math.min(getPreferredWidth(), width);
734 }
735 break;
736 case MeasureSpec.EXACTLY:
737 // If an exact width is specified, still don't exceed any specified maximum width
738 if (mMaxWidth > 0) {
739 width = Math.min(mMaxWidth, width);
740 }
741 break;
742 case MeasureSpec.UNSPECIFIED:
743 // Use maximum width, if specified, else preferred width
744 width = mMaxWidth > 0 ? mMaxWidth : getPreferredWidth();
745 break;
Amith Yamasani5931b1f2010-10-18 16:13:14 -0700746 }
Amith Yamasani167d69a2011-08-12 19:28:37 -0700747 widthMode = MeasureSpec.EXACTLY;
748 super.onMeasure(MeasureSpec.makeMeasureSpec(width, widthMode), heightMeasureSpec);
749 }
750
751 private int getPreferredWidth() {
752 return getContext().getResources()
753 .getDimensionPixelSize(R.dimen.search_view_preferred_width);
Amith Yamasani5931b1f2010-10-18 16:13:14 -0700754 }
755
Amith Yamasani93227752010-09-14 10:10:54 -0700756 private void updateViewsVisibility(final boolean collapsed) {
757 mIconified = collapsed;
Amith Yamasani733cbd52010-09-03 12:21:39 -0700758 // Visibility of views that are visible when collapsed
Amith Yamasani93227752010-09-14 10:10:54 -0700759 final int visCollapsed = collapsed ? VISIBLE : GONE;
Amith Yamasani05944762010-10-08 13:52:38 -0700760 // Is there text in the query
761 final boolean hasText = !TextUtils.isEmpty(mQueryTextView.getText());
Amith Yamasani733cbd52010-09-03 12:21:39 -0700762
763 mSearchButton.setVisibility(visCollapsed);
Amith Yamasani9b2e3022011-01-14 11:34:12 -0800764 updateSubmitButton(hasText);
765 mSearchEditFrame.setVisibility(collapsed ? GONE : VISIBLE);
Amith Yamasanib4569fb2011-07-08 15:25:39 -0700766 mSearchHintIcon.setVisibility(mIconifiedByDefault ? GONE : VISIBLE);
Amith Yamasani4aedb392010-12-15 16:04:57 -0800767 updateCloseButton();
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -0700768 updateVoiceButton(!hasText);
Amith Yamasani9b2e3022011-01-14 11:34:12 -0800769 updateSubmitArea();
Amith Yamasani9b2e3022011-01-14 11:34:12 -0800770 }
771
772 private boolean hasVoiceSearch() {
773 if (mSearchable != null && mSearchable.getVoiceSearchEnabled()) {
774 Intent testIntent = null;
775 if (mSearchable.getVoiceSearchLaunchWebSearch()) {
776 testIntent = mVoiceWebSearchIntent;
777 } else if (mSearchable.getVoiceSearchLaunchRecognizer()) {
778 testIntent = mVoiceAppSearchIntent;
779 }
780 if (testIntent != null) {
781 ResolveInfo ri = getContext().getPackageManager().resolveActivity(testIntent,
782 PackageManager.MATCH_DEFAULT_ONLY);
783 return ri != null;
784 }
785 }
786 return false;
787 }
788
789 private boolean isSubmitAreaEnabled() {
790 return (mSubmitButtonEnabled || mVoiceButtonEnabled) && !isIconified();
791 }
792
793 private void updateSubmitButton(boolean hasText) {
Amith Yamasani79f74302011-03-08 14:16:35 -0800794 int visibility = GONE;
Amith Yamasanicf72ab42011-11-04 13:49:28 -0700795 if (mSubmitButtonEnabled && isSubmitAreaEnabled() && hasFocus()
796 && (hasText || !mVoiceButtonEnabled)) {
Amith Yamasani79f74302011-03-08 14:16:35 -0800797 visibility = VISIBLE;
798 }
799 mSubmitButton.setVisibility(visibility);
Amith Yamasani9b2e3022011-01-14 11:34:12 -0800800 }
801
802 private void updateSubmitArea() {
803 int visibility = GONE;
Amith Yamasani79f74302011-03-08 14:16:35 -0800804 if (isSubmitAreaEnabled()
805 && (mSubmitButton.getVisibility() == VISIBLE
806 || mVoiceButton.getVisibility() == VISIBLE)) {
807 visibility = VISIBLE;
Amith Yamasani9b2e3022011-01-14 11:34:12 -0800808 }
809 mSubmitArea.setVisibility(visibility);
Amith Yamasani733cbd52010-09-03 12:21:39 -0700810 }
811
Amith Yamasani4aedb392010-12-15 16:04:57 -0800812 private void updateCloseButton() {
813 final boolean hasText = !TextUtils.isEmpty(mQueryTextView.getText());
814 // Should we show the close button? It is not shown if there's no focus,
815 // field is not iconified by default and there is no text in it.
Amith Yamasani763bc072011-07-22 11:53:47 -0700816 final boolean showClose = hasText || (mIconifiedByDefault && !mExpandedInActionView);
Amith Yamasani167d69a2011-08-12 19:28:37 -0700817 mCloseButton.setVisibility(showClose ? VISIBLE : GONE);
Amith Yamasani4aedb392010-12-15 16:04:57 -0800818 mCloseButton.getDrawable().setState(hasText ? ENABLED_STATE_SET : EMPTY_STATE_SET);
819 }
820
Amith Yamasania95e4882011-08-17 11:41:37 -0700821 private void postUpdateFocusedState() {
822 post(mUpdateDrawableStateRunnable);
823 }
824
825 private void updateFocusedState() {
826 boolean focused = mQueryTextView.hasFocus();
Amith Yamasani79f74302011-03-08 14:16:35 -0800827 mSearchPlate.getBackground().setState(focused ? FOCUSED_STATE_SET : EMPTY_STATE_SET);
828 mSubmitArea.getBackground().setState(focused ? FOCUSED_STATE_SET : EMPTY_STATE_SET);
Amith Yamasania95e4882011-08-17 11:41:37 -0700829 invalidate();
830 }
831
832 @Override
Amith Yamasania465b2d2011-08-19 13:01:22 -0700833 protected void onDetachedFromWindow() {
Amith Yamasania95e4882011-08-17 11:41:37 -0700834 removeCallbacks(mUpdateDrawableStateRunnable);
Amith Yamasani87907642011-11-03 11:32:44 -0700835 post(mReleaseCursorRunnable);
Amith Yamasania95e4882011-08-17 11:41:37 -0700836 super.onDetachedFromWindow();
Amith Yamasani79f74302011-03-08 14:16:35 -0800837 }
838
Adam Powellccdd4ee2011-07-27 20:05:14 -0700839 private void setImeVisibility(final boolean visible) {
840 if (visible) {
841 post(mShowImeRunnable);
842 } else {
843 removeCallbacks(mShowImeRunnable);
844 InputMethodManager imm = (InputMethodManager)
845 getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
repo sync6a81b822010-09-28 13:00:05 -0700846
Adam Powellccdd4ee2011-07-27 20:05:14 -0700847 if (imm != null) {
Amith Yamasani05944762010-10-08 13:52:38 -0700848 imm.hideSoftInputFromWindow(getWindowToken(), 0);
Amith Yamasani733cbd52010-09-03 12:21:39 -0700849 }
850 }
851 }
852
Amith Yamasanie678f462010-09-15 16:13:43 -0700853 /**
854 * Called by the SuggestionsAdapter
855 * @hide
856 */
857 /* package */void onQueryRefine(CharSequence queryText) {
858 setQuery(queryText);
859 }
860
Amith Yamasani733cbd52010-09-03 12:21:39 -0700861 private final OnClickListener mOnClickListener = new OnClickListener() {
862
863 public void onClick(View v) {
864 if (v == mSearchButton) {
865 onSearchClicked();
866 } else if (v == mCloseButton) {
867 onCloseClicked();
868 } else if (v == mSubmitButton) {
869 onSubmitQuery();
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -0700870 } else if (v == mVoiceButton) {
871 onVoiceClicked();
Amith Yamasanif28d1872011-07-26 12:21:03 -0700872 } else if (v == mQueryTextView) {
873 forceSuggestionQuery();
Amith Yamasani733cbd52010-09-03 12:21:39 -0700874 }
875 }
876 };
877
878 /**
879 * Handles the key down event for dealing with action keys.
880 *
881 * @param keyCode This is the keycode of the typed key, and is the same value as
882 * found in the KeyEvent parameter.
883 * @param event The complete event record for the typed key
884 *
885 * @return true if the event was handled here, or false if not.
886 */
887 @Override
888 public boolean onKeyDown(int keyCode, KeyEvent event) {
889 if (mSearchable == null) {
890 return false;
891 }
892
893 // if it's an action specified by the searchable activity, launch the
894 // entered query with the action key
895 SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
896 if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) {
Amith Yamasani93227752010-09-14 10:10:54 -0700897 launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView.getText()
898 .toString());
Amith Yamasani733cbd52010-09-03 12:21:39 -0700899 return true;
900 }
901
902 return super.onKeyDown(keyCode, event);
903 }
904
Amith Yamasani968ec932010-12-02 14:00:47 -0800905 /**
906 * React to the user typing "enter" or other hardwired keys while typing in
907 * the search box. This handles these special keys while the edit box has
908 * focus.
909 */
910 View.OnKeyListener mTextKeyListener = new View.OnKeyListener() {
911 public boolean onKey(View v, int keyCode, KeyEvent event) {
912 // guard against possible race conditions
913 if (mSearchable == null) {
914 return false;
915 }
916
917 if (DBG) {
918 Log.d(LOG_TAG, "mTextListener.onKey(" + keyCode + "," + event + "), selection: "
919 + mQueryTextView.getListSelection());
920 }
921
922 // If a suggestion is selected, handle enter, search key, and action keys
923 // as presses on the selected suggestion
924 if (mQueryTextView.isPopupShowing()
925 && mQueryTextView.getListSelection() != ListView.INVALID_POSITION) {
926 return onSuggestionsKey(v, keyCode, event);
927 }
928
929 // If there is text in the query box, handle enter, and action keys
930 // The search key is handled by the dialog's onKeyDown().
Jeff Brown4e6319b2010-12-13 10:36:51 -0800931 if (!mQueryTextView.isEmpty() && event.hasNoModifiers()) {
932 if (event.getAction() == KeyEvent.ACTION_UP) {
933 if (keyCode == KeyEvent.KEYCODE_ENTER) {
934 v.cancelLongPress();
Amith Yamasani968ec932010-12-02 14:00:47 -0800935
Jeff Brown4e6319b2010-12-13 10:36:51 -0800936 // Launch as a regular search.
937 launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, mQueryTextView.getText()
938 .toString());
939 return true;
940 }
Amith Yamasani968ec932010-12-02 14:00:47 -0800941 }
942 if (event.getAction() == KeyEvent.ACTION_DOWN) {
943 SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
944 if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) {
945 launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView
946 .getText().toString());
947 return true;
948 }
949 }
950 }
951 return false;
952 }
953 };
954
955 /**
956 * React to the user typing while in the suggestions list. First, check for
957 * action keys. If not handled, try refocusing regular characters into the
958 * EditText.
959 */
960 private boolean onSuggestionsKey(View v, int keyCode, KeyEvent event) {
961 // guard against possible race conditions (late arrival after dismiss)
962 if (mSearchable == null) {
963 return false;
964 }
965 if (mSuggestionsAdapter == null) {
966 return false;
967 }
Jeff Brown4e6319b2010-12-13 10:36:51 -0800968 if (event.getAction() == KeyEvent.ACTION_DOWN && event.hasNoModifiers()) {
Amith Yamasani968ec932010-12-02 14:00:47 -0800969 // First, check for enter or search (both of which we'll treat as a
970 // "click")
Jeff Brown4e6319b2010-12-13 10:36:51 -0800971 if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH
972 || keyCode == KeyEvent.KEYCODE_TAB) {
Amith Yamasani968ec932010-12-02 14:00:47 -0800973 int position = mQueryTextView.getListSelection();
974 return onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null);
975 }
976
977 // Next, check for left/right moves, which we use to "return" the
978 // user to the edit view
979 if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
980 // give "focus" to text editor, with cursor at the beginning if
981 // left key, at end if right key
982 // TODO: Reverse left/right for right-to-left languages, e.g.
983 // Arabic
984 int selPoint = (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) ? 0 : mQueryTextView
985 .length();
986 mQueryTextView.setSelection(selPoint);
987 mQueryTextView.setListSelection(0);
988 mQueryTextView.clearListSelection();
989 mQueryTextView.ensureImeVisible(true);
990
991 return true;
992 }
993
994 // Next, check for an "up and out" move
995 if (keyCode == KeyEvent.KEYCODE_DPAD_UP && 0 == mQueryTextView.getListSelection()) {
996 // TODO: restoreUserQuery();
997 // let ACTV complete the move
998 return false;
999 }
1000
1001 // Next, check for an "action key"
1002 SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
1003 if ((actionKey != null)
1004 && ((actionKey.getSuggestActionMsg() != null) || (actionKey
1005 .getSuggestActionMsgColumn() != null))) {
1006 // launch suggestion using action key column
1007 int position = mQueryTextView.getListSelection();
1008 if (position != ListView.INVALID_POSITION) {
1009 Cursor c = mSuggestionsAdapter.getCursor();
1010 if (c.moveToPosition(position)) {
1011 final String actionMsg = getActionKeyMessage(c, actionKey);
1012 if (actionMsg != null && (actionMsg.length() > 0)) {
1013 return onItemClicked(position, keyCode, actionMsg);
1014 }
1015 }
1016 }
1017 }
1018 }
1019 return false;
1020 }
1021
1022 /**
1023 * For a given suggestion and a given cursor row, get the action message. If
1024 * not provided by the specific row/column, also check for a single
1025 * definition (for the action key).
1026 *
1027 * @param c The cursor providing suggestions
1028 * @param actionKey The actionkey record being examined
1029 *
1030 * @return Returns a string, or null if no action key message for this
1031 * suggestion
1032 */
1033 private static String getActionKeyMessage(Cursor c, SearchableInfo.ActionKeyInfo actionKey) {
1034 String result = null;
1035 // check first in the cursor data, for a suggestion-specific message
1036 final String column = actionKey.getSuggestActionMsgColumn();
1037 if (column != null) {
1038 result = SuggestionsAdapter.getColumnString(c, column);
1039 }
1040 // If the cursor didn't give us a message, see if there's a single
1041 // message defined
1042 // for the actionkey (for all suggestions)
1043 if (result == null) {
1044 result = actionKey.getSuggestActionMsg();
1045 }
1046 return result;
1047 }
1048
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001049 private int getSearchIconId() {
1050 TypedValue outValue = new TypedValue();
1051 getContext().getTheme().resolveAttribute(com.android.internal.R.attr.searchViewSearchIcon,
1052 outValue, true);
1053 return outValue.resourceId;
1054 }
1055
1056 private CharSequence getDecoratedHint(CharSequence hintText) {
1057 // If the field is always expanded, then don't add the search icon to the hint
1058 if (!mIconifiedByDefault) return hintText;
1059
1060 SpannableStringBuilder ssb = new SpannableStringBuilder(" "); // for the icon
1061 ssb.append(hintText);
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001062 Drawable searchIcon = getContext().getDrawable(getSearchIconId());
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001063 int textSize = (int) (mQueryTextView.getTextSize() * 1.25);
1064 searchIcon.setBounds(0, 0, textSize, textSize);
1065 ssb.setSpan(new ImageSpan(searchIcon), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1066 return ssb;
1067 }
1068
Amith Yamasani733cbd52010-09-03 12:21:39 -07001069 private void updateQueryHint() {
1070 if (mQueryHint != null) {
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001071 mQueryTextView.setHint(getDecoratedHint(mQueryHint));
Amith Yamasani733cbd52010-09-03 12:21:39 -07001072 } else if (mSearchable != null) {
1073 CharSequence hint = null;
1074 int hintId = mSearchable.getHintId();
1075 if (hintId != 0) {
1076 hint = getContext().getString(hintId);
1077 }
1078 if (hint != null) {
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001079 mQueryTextView.setHint(getDecoratedHint(hint));
Amith Yamasani733cbd52010-09-03 12:21:39 -07001080 }
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001081 } else {
1082 mQueryTextView.setHint(getDecoratedHint(""));
Amith Yamasani733cbd52010-09-03 12:21:39 -07001083 }
1084 }
1085
1086 /**
1087 * Updates the auto-complete text view.
1088 */
1089 private void updateSearchAutoComplete() {
Amith Yamasani733cbd52010-09-03 12:21:39 -07001090 mQueryTextView.setDropDownAnimationStyle(0); // no animation
Amith Yamasani5931b1f2010-10-18 16:13:14 -07001091 mQueryTextView.setThreshold(mSearchable.getSuggestThreshold());
Amith Yamasani5607a382011-08-09 14:16:37 -07001092 mQueryTextView.setImeOptions(mSearchable.getImeOptions());
1093 int inputType = mSearchable.getInputType();
1094 // We only touch this if the input type is set up for text (which it almost certainly
1095 // should be, in the case of search!)
1096 if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) {
1097 // The existence of a suggestions authority is the proxy for "suggestions
1098 // are available here"
1099 inputType &= ~InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE;
1100 if (mSearchable.getSuggestAuthority() != null) {
1101 inputType |= InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE;
Satoshi Kataoka9ce11162012-06-04 17:12:08 +09001102 // TYPE_TEXT_FLAG_AUTO_COMPLETE means that the text editor is performing
1103 // auto-completion based on its own semantics, which it will present to the user
1104 // as they type. This generally means that the input method should not show its
1105 // own candidates, and the spell checker should not be in action. The text editor
1106 // supplies its candidates by calling InputMethodManager.displayCompletions(),
1107 // which in turn will call InputMethodSession.displayCompletions().
1108 inputType |= InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
Amith Yamasani5607a382011-08-09 14:16:37 -07001109 }
1110 }
1111 mQueryTextView.setInputType(inputType);
Amith Yamasani87907642011-11-03 11:32:44 -07001112 if (mSuggestionsAdapter != null) {
1113 mSuggestionsAdapter.changeCursor(null);
1114 }
Amith Yamasani733cbd52010-09-03 12:21:39 -07001115 // attach the suggestions adapter, if suggestions are available
1116 // The existence of a suggestions authority is the proxy for "suggestions available here"
1117 if (mSearchable.getSuggestAuthority() != null) {
1118 mSuggestionsAdapter = new SuggestionsAdapter(getContext(),
1119 this, mSearchable, mOutsideDrawablesCache);
1120 mQueryTextView.setAdapter(mSuggestionsAdapter);
Amith Yamasanie678f462010-09-15 16:13:43 -07001121 ((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement(
1122 mQueryRefinement ? SuggestionsAdapter.REFINE_ALL
1123 : SuggestionsAdapter.REFINE_BY_ENTRY);
Amith Yamasani733cbd52010-09-03 12:21:39 -07001124 }
1125 }
1126
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -07001127 /**
1128 * Update the visibility of the voice button. There are actually two voice search modes,
1129 * either of which will activate the button.
1130 * @param empty whether the search query text field is empty. If it is, then the other
Amith Yamasani79f74302011-03-08 14:16:35 -08001131 * criteria apply to make the voice button visible.
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -07001132 */
1133 private void updateVoiceButton(boolean empty) {
Amith Yamasani79f74302011-03-08 14:16:35 -08001134 int visibility = GONE;
Amith Yamasani167d69a2011-08-12 19:28:37 -07001135 if (mVoiceButtonEnabled && !isIconified() && empty) {
Amith Yamasani9b2e3022011-01-14 11:34:12 -08001136 visibility = VISIBLE;
1137 mSubmitButton.setVisibility(GONE);
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -07001138 }
1139 mVoiceButton.setVisibility(visibility);
1140 }
1141
Amith Yamasani733cbd52010-09-03 12:21:39 -07001142 private final OnEditorActionListener mOnEditorActionListener = new OnEditorActionListener() {
1143
1144 /**
1145 * Called when the input method default action key is pressed.
1146 */
1147 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
1148 onSubmitQuery();
1149 return true;
1150 }
1151 };
1152
1153 private void onTextChanged(CharSequence newText) {
1154 CharSequence text = mQueryTextView.getText();
Amith Yamasani068d73c2011-05-27 15:15:14 -07001155 mUserQuery = text;
Amith Yamasani733cbd52010-09-03 12:21:39 -07001156 boolean hasText = !TextUtils.isEmpty(text);
Amith Yamasanicf72ab42011-11-04 13:49:28 -07001157 updateSubmitButton(hasText);
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -07001158 updateVoiceButton(!hasText);
Amith Yamasani73e00df2010-12-16 16:31:29 -08001159 updateCloseButton();
Amith Yamasani9b2e3022011-01-14 11:34:12 -08001160 updateSubmitArea();
Amith Yamasanib47c4fd2011-08-04 14:30:07 -07001161 if (mOnQueryChangeListener != null && !TextUtils.equals(newText, mOldQueryText)) {
Adam Powell01f21352011-01-20 18:30:10 -08001162 mOnQueryChangeListener.onQueryTextChange(newText.toString());
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -07001163 }
Amith Yamasanib47c4fd2011-08-04 14:30:07 -07001164 mOldQueryText = newText.toString();
Amith Yamasani733cbd52010-09-03 12:21:39 -07001165 }
1166
1167 private void onSubmitQuery() {
1168 CharSequence query = mQueryTextView.getText();
Amith Yamasani6a7421b2011-07-27 11:55:53 -07001169 if (query != null && TextUtils.getTrimmedLength(query) > 0) {
Amith Yamasani733cbd52010-09-03 12:21:39 -07001170 if (mOnQueryChangeListener == null
Adam Powell01f21352011-01-20 18:30:10 -08001171 || !mOnQueryChangeListener.onQueryTextSubmit(query.toString())) {
Amith Yamasani733cbd52010-09-03 12:21:39 -07001172 if (mSearchable != null) {
1173 launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString());
Amith Yamasani05944762010-10-08 13:52:38 -07001174 setImeVisibility(false);
Amith Yamasani733cbd52010-09-03 12:21:39 -07001175 }
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -07001176 dismissSuggestions();
Amith Yamasani733cbd52010-09-03 12:21:39 -07001177 }
1178 }
1179 }
1180
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -07001181 private void dismissSuggestions() {
1182 mQueryTextView.dismissDropDown();
1183 }
1184
Amith Yamasani733cbd52010-09-03 12:21:39 -07001185 private void onCloseClicked() {
Amith Yamasani24652982011-06-23 16:16:05 -07001186 CharSequence text = mQueryTextView.getText();
1187 if (TextUtils.isEmpty(text)) {
1188 if (mIconifiedByDefault) {
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001189 // If the app doesn't override the close behavior
1190 if (mOnCloseListener == null || !mOnCloseListener.onClose()) {
1191 // hide the keyboard and remove focus
1192 clearFocus();
1193 // collapse the search field
1194 updateViewsVisibility(true);
1195 }
Amith Yamasani05944762010-10-08 13:52:38 -07001196 }
Amith Yamasani24652982011-06-23 16:16:05 -07001197 } else {
1198 mQueryTextView.setText("");
1199 mQueryTextView.requestFocus();
1200 setImeVisibility(true);
1201 }
1202
Amith Yamasani733cbd52010-09-03 12:21:39 -07001203 }
1204
1205 private void onSearchClicked() {
Amith Yamasani733cbd52010-09-03 12:21:39 -07001206 updateViewsVisibility(false);
Amith Yamasani7f8aef62011-01-25 11:58:09 -08001207 mQueryTextView.requestFocus();
Amith Yamasani05944762010-10-08 13:52:38 -07001208 setImeVisibility(true);
Amith Yamasani48385482010-12-03 14:43:52 -08001209 if (mOnSearchClickListener != null) {
1210 mOnSearchClickListener.onClick(this);
1211 }
Amith Yamasani733cbd52010-09-03 12:21:39 -07001212 }
1213
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -07001214 private void onVoiceClicked() {
1215 // guard against possible race conditions
1216 if (mSearchable == null) {
1217 return;
1218 }
1219 SearchableInfo searchable = mSearchable;
1220 try {
1221 if (searchable.getVoiceSearchLaunchWebSearch()) {
1222 Intent webSearchIntent = createVoiceWebSearchIntent(mVoiceWebSearchIntent,
1223 searchable);
1224 getContext().startActivity(webSearchIntent);
1225 } else if (searchable.getVoiceSearchLaunchRecognizer()) {
1226 Intent appSearchIntent = createVoiceAppSearchIntent(mVoiceAppSearchIntent,
1227 searchable);
1228 getContext().startActivity(appSearchIntent);
1229 }
1230 } catch (ActivityNotFoundException e) {
1231 // Should not happen, since we check the availability of
1232 // voice search before showing the button. But just in case...
1233 Log.w(LOG_TAG, "Could not find voice search activity");
1234 }
1235 }
1236
Amith Yamasani4aedb392010-12-15 16:04:57 -08001237 void onTextFocusChanged() {
Amith Yamasani79f74302011-03-08 14:16:35 -08001238 updateViewsVisibility(isIconified());
Amith Yamasania95e4882011-08-17 11:41:37 -07001239 // Delayed update to make sure that the focus has settled down and window focus changes
1240 // don't affect it. A synchronous update was not working.
1241 postUpdateFocusedState();
Amith Yamasanif28d1872011-07-26 12:21:03 -07001242 if (mQueryTextView.hasFocus()) {
1243 forceSuggestionQuery();
1244 }
Amith Yamasani4aedb392010-12-15 16:04:57 -08001245 }
1246
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001247 @Override
Amith Yamasania95e4882011-08-17 11:41:37 -07001248 public void onWindowFocusChanged(boolean hasWindowFocus) {
1249 super.onWindowFocusChanged(hasWindowFocus);
1250
1251 postUpdateFocusedState();
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001252 }
1253
Amith Yamasani763bc072011-07-22 11:53:47 -07001254 /**
1255 * {@inheritDoc}
1256 */
1257 @Override
1258 public void onActionViewCollapsed() {
Adam Powell99d0ce92012-12-10 13:11:47 -08001259 setQuery("", false);
Amith Yamasani10da5902011-07-26 16:14:26 -07001260 clearFocus();
1261 updateViewsVisibility(true);
Adam Powell53f56c42011-09-25 13:46:15 -07001262 mQueryTextView.setImeOptions(mCollapsedImeOptions);
Amith Yamasani763bc072011-07-22 11:53:47 -07001263 mExpandedInActionView = false;
1264 }
1265
1266 /**
1267 * {@inheritDoc}
1268 */
1269 @Override
1270 public void onActionViewExpanded() {
Amith Yamasani434c73f2011-11-01 11:44:50 -07001271 if (mExpandedInActionView) return;
1272
Amith Yamasani763bc072011-07-22 11:53:47 -07001273 mExpandedInActionView = true;
Adam Powell53f56c42011-09-25 13:46:15 -07001274 mCollapsedImeOptions = mQueryTextView.getImeOptions();
1275 mQueryTextView.setImeOptions(mCollapsedImeOptions | EditorInfo.IME_FLAG_NO_FULLSCREEN);
Amith Yamasani87907642011-11-03 11:32:44 -07001276 mQueryTextView.setText("");
Amith Yamasani763bc072011-07-22 11:53:47 -07001277 setIconified(false);
1278 }
1279
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -08001280 @Override
1281 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
1282 super.onInitializeAccessibilityEvent(event);
1283 event.setClassName(SearchView.class.getName());
1284 }
1285
1286 @Override
1287 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
1288 super.onInitializeAccessibilityNodeInfo(info);
1289 info.setClassName(SearchView.class.getName());
1290 }
1291
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001292 private void adjustDropDownSizeAndPosition() {
1293 if (mDropDownAnchor.getWidth() > 1) {
1294 Resources res = getContext().getResources();
1295 int anchorPadding = mSearchPlate.getPaddingLeft();
1296 Rect dropDownPadding = new Rect();
Fabrice Di Meglio3a69bea2012-07-26 13:50:10 -07001297 final boolean isLayoutRtl = isLayoutRtl();
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001298 int iconOffset = mIconifiedByDefault
1299 ? res.getDimensionPixelSize(R.dimen.dropdownitem_icon_width)
1300 + res.getDimensionPixelSize(R.dimen.dropdownitem_text_padding_left)
1301 : 0;
1302 mQueryTextView.getDropDownBackground().getPadding(dropDownPadding);
Fabrice Di Meglio3a69bea2012-07-26 13:50:10 -07001303 int offset;
1304 if (isLayoutRtl) {
1305 offset = - dropDownPadding.left;
1306 } else {
1307 offset = anchorPadding - (dropDownPadding.left + iconOffset);
1308 }
1309 mQueryTextView.setDropDownHorizontalOffset(offset);
1310 final int width = mDropDownAnchor.getWidth() + dropDownPadding.left
1311 + dropDownPadding.right + iconOffset - anchorPadding;
1312 mQueryTextView.setDropDownWidth(width);
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001313 }
1314 }
1315
Amith Yamasani968ec932010-12-02 14:00:47 -08001316 private boolean onItemClicked(int position, int actionKey, String actionMsg) {
1317 if (mOnSuggestionListener == null
Adam Powell01f21352011-01-20 18:30:10 -08001318 || !mOnSuggestionListener.onSuggestionClick(position)) {
Amith Yamasani968ec932010-12-02 14:00:47 -08001319 launchSuggestion(position, KeyEvent.KEYCODE_UNKNOWN, null);
1320 setImeVisibility(false);
1321 dismissSuggestions();
1322 return true;
1323 }
1324 return false;
1325 }
1326
1327 private boolean onItemSelected(int position) {
1328 if (mOnSuggestionListener == null
Adam Powell01f21352011-01-20 18:30:10 -08001329 || !mOnSuggestionListener.onSuggestionSelect(position)) {
Amith Yamasani968ec932010-12-02 14:00:47 -08001330 rewriteQueryFromSuggestion(position);
1331 return true;
1332 }
1333 return false;
1334 }
1335
Amith Yamasani733cbd52010-09-03 12:21:39 -07001336 private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
1337
1338 /**
1339 * Implements OnItemClickListener
1340 */
1341 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Amith Yamasani968ec932010-12-02 14:00:47 -08001342 if (DBG) Log.d(LOG_TAG, "onItemClick() position " + position);
1343 onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null);
Amith Yamasani733cbd52010-09-03 12:21:39 -07001344 }
1345 };
1346
1347 private final OnItemSelectedListener mOnItemSelectedListener = new OnItemSelectedListener() {
1348
1349 /**
1350 * Implements OnItemSelectedListener
1351 */
1352 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Amith Yamasani968ec932010-12-02 14:00:47 -08001353 if (DBG) Log.d(LOG_TAG, "onItemSelected() position " + position);
1354 SearchView.this.onItemSelected(position);
Amith Yamasani733cbd52010-09-03 12:21:39 -07001355 }
1356
1357 /**
1358 * Implements OnItemSelectedListener
1359 */
1360 public void onNothingSelected(AdapterView<?> parent) {
1361 if (DBG)
1362 Log.d(LOG_TAG, "onNothingSelected()");
1363 }
1364 };
1365
Fabrice Di Meglio3a69bea2012-07-26 13:50:10 -07001366 @Override
Fabrice Di Meglio343e1132012-09-28 18:01:17 -07001367 public void onRtlPropertiesChanged(int layoutDirection) {
1368 mQueryTextView.setLayoutDirection(layoutDirection);
Fabrice Di Meglio3a69bea2012-07-26 13:50:10 -07001369 }
1370
Amith Yamasani733cbd52010-09-03 12:21:39 -07001371 /**
1372 * Query rewriting.
1373 */
1374 private void rewriteQueryFromSuggestion(int position) {
1375 CharSequence oldQuery = mQueryTextView.getText();
1376 Cursor c = mSuggestionsAdapter.getCursor();
1377 if (c == null) {
1378 return;
1379 }
1380 if (c.moveToPosition(position)) {
1381 // Get the new query from the suggestion.
1382 CharSequence newQuery = mSuggestionsAdapter.convertToString(c);
1383 if (newQuery != null) {
1384 // The suggestion rewrites the query.
1385 // Update the text field, without getting new suggestions.
1386 setQuery(newQuery);
1387 } else {
1388 // The suggestion does not rewrite the query, restore the user's query.
1389 setQuery(oldQuery);
1390 }
1391 } else {
1392 // We got a bad position, restore the user's query.
1393 setQuery(oldQuery);
1394 }
1395 }
1396
1397 /**
1398 * Launches an intent based on a suggestion.
1399 *
1400 * @param position The index of the suggestion to create the intent from.
1401 * @param actionKey The key code of the action key that was pressed,
1402 * or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
1403 * @param actionMsg The message for the action key that was pressed,
1404 * or <code>null</code> if none.
1405 * @return true if a successful launch, false if could not (e.g. bad position).
1406 */
1407 private boolean launchSuggestion(int position, int actionKey, String actionMsg) {
1408 Cursor c = mSuggestionsAdapter.getCursor();
1409 if ((c != null) && c.moveToPosition(position)) {
1410
1411 Intent intent = createIntentFromSuggestion(c, actionKey, actionMsg);
1412
1413 // launch the intent
1414 launchIntent(intent);
1415
1416 return true;
1417 }
1418 return false;
1419 }
1420
1421 /**
1422 * Launches an intent, including any special intent handling.
1423 */
1424 private void launchIntent(Intent intent) {
1425 if (intent == null) {
1426 return;
1427 }
1428 try {
1429 // If the intent was created from a suggestion, it will always have an explicit
1430 // component here.
1431 getContext().startActivity(intent);
1432 } catch (RuntimeException ex) {
1433 Log.e(LOG_TAG, "Failed launch activity: " + intent, ex);
1434 }
1435 }
1436
1437 /**
1438 * Sets the text in the query box, without updating the suggestions.
1439 */
1440 private void setQuery(CharSequence query) {
Amith Yamasanie678f462010-09-15 16:13:43 -07001441 mQueryTextView.setText(query, true);
1442 // Move the cursor to the end
1443 mQueryTextView.setSelection(TextUtils.isEmpty(query) ? 0 : query.length());
Amith Yamasani733cbd52010-09-03 12:21:39 -07001444 }
1445
1446 private void launchQuerySearch(int actionKey, String actionMsg, String query) {
1447 String action = Intent.ACTION_SEARCH;
Amith Yamasanie678f462010-09-15 16:13:43 -07001448 Intent intent = createIntent(action, null, null, query, actionKey, actionMsg);
Amith Yamasani733cbd52010-09-03 12:21:39 -07001449 getContext().startActivity(intent);
1450 }
1451
1452 /**
1453 * Constructs an intent from the given information and the search dialog state.
1454 *
1455 * @param action Intent action.
1456 * @param data Intent data, or <code>null</code>.
1457 * @param extraData Data for {@link SearchManager#EXTRA_DATA_KEY} or <code>null</code>.
1458 * @param query Intent query, or <code>null</code>.
Amith Yamasani733cbd52010-09-03 12:21:39 -07001459 * @param actionKey The key code of the action key that was pressed,
1460 * or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
1461 * @param actionMsg The message for the action key that was pressed,
1462 * or <code>null</code> if none.
1463 * @param mode The search mode, one of the acceptable values for
1464 * {@link SearchManager#SEARCH_MODE}, or {@code null}.
1465 * @return The intent.
1466 */
1467 private Intent createIntent(String action, Uri data, String extraData, String query,
Amith Yamasanie678f462010-09-15 16:13:43 -07001468 int actionKey, String actionMsg) {
Amith Yamasani733cbd52010-09-03 12:21:39 -07001469 // Now build the Intent
1470 Intent intent = new Intent(action);
1471 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1472 // We need CLEAR_TOP to avoid reusing an old task that has other activities
1473 // on top of the one we want. We don't want to do this in in-app search though,
1474 // as it can be destructive to the activity stack.
1475 if (data != null) {
1476 intent.setData(data);
1477 }
Amith Yamasani068d73c2011-05-27 15:15:14 -07001478 intent.putExtra(SearchManager.USER_QUERY, mUserQuery);
Amith Yamasani733cbd52010-09-03 12:21:39 -07001479 if (query != null) {
1480 intent.putExtra(SearchManager.QUERY, query);
1481 }
1482 if (extraData != null) {
1483 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
1484 }
Amith Yamasani940ef382011-03-02 18:43:23 -08001485 if (mAppSearchData != null) {
1486 intent.putExtra(SearchManager.APP_DATA, mAppSearchData);
1487 }
Amith Yamasani733cbd52010-09-03 12:21:39 -07001488 if (actionKey != KeyEvent.KEYCODE_UNKNOWN) {
1489 intent.putExtra(SearchManager.ACTION_KEY, actionKey);
1490 intent.putExtra(SearchManager.ACTION_MSG, actionMsg);
1491 }
1492 intent.setComponent(mSearchable.getSearchActivity());
1493 return intent;
1494 }
1495
1496 /**
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -07001497 * Create and return an Intent that can launch the voice search activity for web search.
1498 */
1499 private Intent createVoiceWebSearchIntent(Intent baseIntent, SearchableInfo searchable) {
1500 Intent voiceIntent = new Intent(baseIntent);
1501 ComponentName searchActivity = searchable.getSearchActivity();
1502 voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null
1503 : searchActivity.flattenToShortString());
1504 return voiceIntent;
1505 }
1506
1507 /**
1508 * Create and return an Intent that can launch the voice search activity, perform a specific
1509 * voice transcription, and forward the results to the searchable activity.
1510 *
1511 * @param baseIntent The voice app search intent to start from
1512 * @return A completely-configured intent ready to send to the voice search activity
1513 */
1514 private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) {
1515 ComponentName searchActivity = searchable.getSearchActivity();
1516
1517 // create the necessary intent to set up a search-and-forward operation
1518 // in the voice search system. We have to keep the bundle separate,
1519 // because it becomes immutable once it enters the PendingIntent
1520 Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
1521 queryIntent.setComponent(searchActivity);
1522 PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent,
1523 PendingIntent.FLAG_ONE_SHOT);
1524
1525 // Now set up the bundle that will be inserted into the pending intent
1526 // when it's time to do the search. We always build it here (even if empty)
1527 // because the voice search activity will always need to insert "QUERY" into
1528 // it anyway.
1529 Bundle queryExtras = new Bundle();
Jorge Ruesga1bcfe842012-09-03 01:26:59 +02001530 if (mAppSearchData != null) {
1531 queryExtras.putParcelable(SearchManager.APP_DATA, mAppSearchData);
1532 }
Amith Yamasaniebcf5a3a2010-10-13 11:35:24 -07001533
1534 // Now build the intent to launch the voice search. Add all necessary
1535 // extras to launch the voice recognizer, and then all the necessary extras
1536 // to forward the results to the searchable activity
1537 Intent voiceIntent = new Intent(baseIntent);
1538
1539 // Add all of the configuration options supplied by the searchable's metadata
1540 String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM;
1541 String prompt = null;
1542 String language = null;
1543 int maxResults = 1;
1544
1545 Resources resources = getResources();
1546 if (searchable.getVoiceLanguageModeId() != 0) {
1547 languageModel = resources.getString(searchable.getVoiceLanguageModeId());
1548 }
1549 if (searchable.getVoicePromptTextId() != 0) {
1550 prompt = resources.getString(searchable.getVoicePromptTextId());
1551 }
1552 if (searchable.getVoiceLanguageId() != 0) {
1553 language = resources.getString(searchable.getVoiceLanguageId());
1554 }
1555 if (searchable.getVoiceMaxResults() != 0) {
1556 maxResults = searchable.getVoiceMaxResults();
1557 }
1558 voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel);
1559 voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
1560 voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
1561 voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
1562 voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null
1563 : searchActivity.flattenToShortString());
1564
1565 // Add the values that configure forwarding the results
1566 voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
1567 voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);
1568
1569 return voiceIntent;
1570 }
1571
1572 /**
Amith Yamasani733cbd52010-09-03 12:21:39 -07001573 * When a particular suggestion has been selected, perform the various lookups required
1574 * to use the suggestion. This includes checking the cursor for suggestion-specific data,
1575 * and/or falling back to the XML for defaults; It also creates REST style Uri data when
1576 * the suggestion includes a data id.
1577 *
1578 * @param c The suggestions cursor, moved to the row of the user's selection
1579 * @param actionKey The key code of the action key that was pressed,
1580 * or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
1581 * @param actionMsg The message for the action key that was pressed,
1582 * or <code>null</code> if none.
1583 * @return An intent for the suggestion at the cursor's position.
1584 */
1585 private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) {
1586 try {
1587 // use specific action if supplied, or default action if supplied, or fixed default
1588 String action = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION);
1589
Amith Yamasani733cbd52010-09-03 12:21:39 -07001590 if (action == null) {
1591 action = mSearchable.getSuggestIntentAction();
1592 }
1593 if (action == null) {
1594 action = Intent.ACTION_SEARCH;
1595 }
1596
1597 // use specific data if supplied, or default data if supplied
1598 String data = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA);
1599 if (data == null) {
1600 data = mSearchable.getSuggestIntentData();
1601 }
1602 // then, if an ID was provided, append it.
1603 if (data != null) {
1604 String id = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
1605 if (id != null) {
1606 data = data + "/" + Uri.encode(id);
1607 }
1608 }
1609 Uri dataUri = (data == null) ? null : Uri.parse(data);
1610
Amith Yamasani733cbd52010-09-03 12:21:39 -07001611 String query = getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY);
1612 String extraData = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
1613
Amith Yamasanie678f462010-09-15 16:13:43 -07001614 return createIntent(action, dataUri, extraData, query, actionKey, actionMsg);
Amith Yamasani733cbd52010-09-03 12:21:39 -07001615 } catch (RuntimeException e ) {
1616 int rowNum;
1617 try { // be really paranoid now
1618 rowNum = c.getPosition();
1619 } catch (RuntimeException e2 ) {
1620 rowNum = -1;
1621 }
Jake Wharton73af4512012-07-06 23:15:44 -07001622 Log.w(LOG_TAG, "Search suggestions cursor at row " + rowNum +
1623 " returned exception.", e);
Amith Yamasani733cbd52010-09-03 12:21:39 -07001624 return null;
1625 }
1626 }
1627
Amith Yamasanif28d1872011-07-26 12:21:03 -07001628 private void forceSuggestionQuery() {
1629 mQueryTextView.doBeforeTextChanged();
1630 mQueryTextView.doAfterTextChanged();
1631 }
1632
Amith Yamasani968ec932010-12-02 14:00:47 -08001633 static boolean isLandscapeMode(Context context) {
1634 return context.getResources().getConfiguration().orientation
1635 == Configuration.ORIENTATION_LANDSCAPE;
1636 }
1637
Amith Yamasani733cbd52010-09-03 12:21:39 -07001638 /**
1639 * Callback to watch the text field for empty/non-empty
1640 */
1641 private TextWatcher mTextWatcher = new TextWatcher() {
1642
1643 public void beforeTextChanged(CharSequence s, int start, int before, int after) { }
1644
1645 public void onTextChanged(CharSequence s, int start,
1646 int before, int after) {
1647 SearchView.this.onTextChanged(s);
1648 }
1649
1650 public void afterTextChanged(Editable s) {
1651 }
1652 };
Amith Yamasani968ec932010-12-02 14:00:47 -08001653
1654 /**
1655 * Local subclass for AutoCompleteTextView.
1656 * @hide
1657 */
1658 public static class SearchAutoComplete extends AutoCompleteTextView {
1659
1660 private int mThreshold;
1661 private SearchView mSearchView;
1662
1663 public SearchAutoComplete(Context context) {
1664 super(context);
1665 mThreshold = getThreshold();
1666 }
1667
1668 public SearchAutoComplete(Context context, AttributeSet attrs) {
1669 super(context, attrs);
1670 mThreshold = getThreshold();
1671 }
1672
Alan Viverette617feb92013-09-09 18:09:13 -07001673 public SearchAutoComplete(Context context, AttributeSet attrs, int defStyleAttrs) {
1674 super(context, attrs, defStyleAttrs);
1675 mThreshold = getThreshold();
1676 }
1677
1678 public SearchAutoComplete(
1679 Context context, AttributeSet attrs, int defStyleAttrs, int defStyleRes) {
1680 super(context, attrs, defStyleAttrs, defStyleRes);
Amith Yamasani968ec932010-12-02 14:00:47 -08001681 mThreshold = getThreshold();
1682 }
1683
1684 void setSearchView(SearchView searchView) {
1685 mSearchView = searchView;
1686 }
1687
1688 @Override
1689 public void setThreshold(int threshold) {
1690 super.setThreshold(threshold);
1691 mThreshold = threshold;
1692 }
1693
1694 /**
1695 * Returns true if the text field is empty, or contains only whitespace.
1696 */
1697 private boolean isEmpty() {
1698 return TextUtils.getTrimmedLength(getText()) == 0;
1699 }
1700
1701 /**
1702 * We override this method to avoid replacing the query box text when a
1703 * suggestion is clicked.
1704 */
1705 @Override
1706 protected void replaceText(CharSequence text) {
1707 }
1708
1709 /**
1710 * We override this method to avoid an extra onItemClick being called on
1711 * the drop-down's OnItemClickListener by
1712 * {@link AutoCompleteTextView#onKeyUp(int, KeyEvent)} when an item is
1713 * clicked with the trackball.
1714 */
1715 @Override
1716 public void performCompletion() {
1717 }
1718
1719 /**
1720 * We override this method to be sure and show the soft keyboard if
1721 * appropriate when the TextView has focus.
1722 */
1723 @Override
1724 public void onWindowFocusChanged(boolean hasWindowFocus) {
1725 super.onWindowFocusChanged(hasWindowFocus);
1726
Amith Yamasaniacd8d2d2010-12-06 15:50:23 -08001727 if (hasWindowFocus && mSearchView.hasFocus() && getVisibility() == VISIBLE) {
Amith Yamasani968ec932010-12-02 14:00:47 -08001728 InputMethodManager inputManager = (InputMethodManager) getContext()
1729 .getSystemService(Context.INPUT_METHOD_SERVICE);
1730 inputManager.showSoftInput(this, 0);
1731 // If in landscape mode, then make sure that
1732 // the ime is in front of the dropdown.
1733 if (isLandscapeMode(getContext())) {
1734 ensureImeVisible(true);
1735 }
1736 }
1737 }
1738
Amith Yamasani4aedb392010-12-15 16:04:57 -08001739 @Override
1740 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
1741 super.onFocusChanged(focused, direction, previouslyFocusedRect);
1742 mSearchView.onTextFocusChanged();
1743 }
1744
Amith Yamasani968ec932010-12-02 14:00:47 -08001745 /**
1746 * We override this method so that we can allow a threshold of zero,
1747 * which ACTV does not.
1748 */
1749 @Override
1750 public boolean enoughToFilter() {
1751 return mThreshold <= 0 || super.enoughToFilter();
1752 }
Amith Yamasanib4569fb2011-07-08 15:25:39 -07001753
1754 @Override
1755 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
1756 if (keyCode == KeyEvent.KEYCODE_BACK) {
1757 // special case for the back key, we do not even try to send it
1758 // to the drop down list but instead, consume it immediately
1759 if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
1760 KeyEvent.DispatcherState state = getKeyDispatcherState();
1761 if (state != null) {
1762 state.startTracking(event, this);
1763 }
1764 return true;
1765 } else if (event.getAction() == KeyEvent.ACTION_UP) {
1766 KeyEvent.DispatcherState state = getKeyDispatcherState();
1767 if (state != null) {
1768 state.handleUpEvent(event);
1769 }
1770 if (event.isTracking() && !event.isCanceled()) {
1771 mSearchView.clearFocus();
1772 mSearchView.setImeVisibility(false);
1773 return true;
1774 }
1775 }
1776 }
1777 return super.onKeyPreIme(keyCode, event);
1778 }
1779
Amith Yamasani968ec932010-12-02 14:00:47 -08001780 }
Amith Yamasani05944762010-10-08 13:52:38 -07001781}