I am using the Search interface in andriod, and folowing the android guide I have set up the the interface.
I create a SearchableActivity which will handle both the user input the search result.
Now I meet a problem in that when user input something in the SearchView
and hit the search key, the Search requset will be submited, then I will receive the query string and do the search, but at this moment, the text in the SearchView
was changed to the default SearchHit
value while I want it to be the query string.
So I tried to use the searchView.setQuery(query, false);
, but it does not work, what's the problem?
The core Activity codes:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map_activity_layout); Log.d("map", "create"); handleIntent(getIntent()); } public void onNewIntent(Intent intent) { setIntent(intent); handleIntent(intent); } private void handleIntent(Intent intent) { Log.d("map", "handleIntent"); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); //try search Log.d("map", "search and set query:" + query); searchView.setQuery(query, false); // reset the value in of the SearchView } }
The AndroidManifest.xml:
<activity android:name=".ui.MapActivity" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" /> </activity>
I suggest you to delay the setting until the next event loop (add it to the message queue), so the code may looks like this:
private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { final String query = intent.getStringExtra(SearchManager.QUERY); searchView.post(new Runnable() { @Override public void run() { // Important! Make sure searchView has been initialized // and referenced to the correct (current) SearchView. // Config changes (e.g. screen rotation) may make the // variable value null. searchView.setQuery(query, false); } }; } }
This doesn't work
mSearchView.setQuery(mKeyword, true); MenuItemCompat.expandActionView(mMenuSearch);
This does
MenuItemCompat.expandActionView(mMenuSearch); mSearchView.setQuery(mKeyword, true);
It seems it only remembers it after you expanded the action view. I'm using MenuItemCompat just for backwards compatibility
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With