Android: Show search query in SearchView of a SearchActivity - android

I have few activities in my app which are meant to perform some specific tasks.
I would like to have a search features on almost all of these activities.
My design is as below:
Activity1: With SearchView widget in Actionbar
Activity2: With SearchView widget in Actionbar
SearchActivity: Which perform the search and display results in ListView.
I have done necessary configuration in my manifest file for the SearchActivity.
When I touch on the search icon(magnifying glass), the SearchView gets expanded to allow user to enter the query,then user trigger the search and search intent got delivered to the SearchActivity.
Since the user originally entered the search query on Activity, I don't see the query and SearchView in my SearchActivity (this is basically required to allow user to perform further searches).
I understand that to do so I will also need a SearchView in my SearchActivity too, but How to pre-populate it with the query entered in previous activity and show in expanded state ?

I usually do things like that (plus hving the adapter implements Filterable):
public class ActivityFiltrable extends SherlockFragmentActivity implements OnQueryTextListener{
protected String _searchCurrentQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity);
// ABS
ActionBar bar = getSupportActionBar();
bar.setTitle(R.string.tle_search);
bar.setDisplayHomeAsUpEnabled(true);
//DO STUFF
super.onCreate(savedInstanceState);
}
#Override
protected void onDestroy() {
closeKeyboard(this);
super.onDestroy();
}
#Override
public void onBackPressed() {
finish();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
getSupportMenuInflater().inflate(R.menu.action_bar_search, menu);
// SEARCH MENUITEM
MenuItem searchItem = menu.findItem(R.id.menu_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
return super.onPrepareOptionsMenu(menu);
}
public static void closeKeyboard(Context context) {
try {
InputMethodManager inputManager = (InputMethodManager) ((SherlockFragmentActivity) context).getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(((SherlockFragmentActivity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
catch (Exception e) {
// TODO:ERROR CLOSING KEYBOARD
}
}
/**
* SEARCH
*/
#Override
public boolean onQueryTextSubmit(String query) {
searchAction(query);
closeKeyboard(this);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
searchAction(newText);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (item.getItemId() == android.R.id.home) {
finish();
// overridePendingTransition(R.animator.anim_left, R.animator.anim_right);
return true;
}
break;
}
protected void searchAction(String query) {
_searchCurrentQuery = query.toString();
EtablissementApplication._adapterFilterSearch.getFilter().filter(_searchCurrentQuery);
}
}

Related

How to replace Android Toolbar icons programmatically?

I have a ListView and a Toolbar above of it in my Activity. I want to replace the Toolbar default icons (search and settings) with delete and edit icons when clicking an item of the ListView to perform some action.
So what I've understood from your question, you're looking for ActionMode which might serve your purpose.
So here's an implementation guideline.
Declare an ActionMode in your Activity and let your Activity to implement ActionMode.Callback.
public class YourActivity extends AppCompatActivity implements ActionMode.Callback {
// Declare ActionMode here
private ActionMode actionMode;
// Now implement the callback functions for ActionMode
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onCreateActionMode(final ActionMode actionMode, Menu menu) {
MenuInflater inflater = actionMode.getMenuInflater();
// Inflate your menu here
inflater.inflate(R.menu.list_item_click_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_delete:
// Do something
actionMode.finish();
return true;
case R.id.action_edit:
// Do something
actionMode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
try {
this.actionMode = null;
// Do something. Reset the views maybe?
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now to initiate your ActionMode you need to have this in your onClick function of the list item.
listItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (actionMode != null) {
return true;
}
// Show ActionMode
actionMode = startSupportActionMode(this);
actionMode.invalidate();
}
});
You may need to reset the ActionMode sometimes.
#Override
public void onResume() {
super.onResume();
if (actionMode != null) {
actionMode.finish();
actionMode = null;
}
}

Android:Text in searchView disappears on Configuration Change

The text i enter in searchView disappears on config change.
I am already handling the config change but still its not working.
As i have used fragments, so below code is written inside fragment.
Please solve my problem with respect to that.
My problem is i am not able to retrieve savedInstance in onActivityCreated method
Below is my code:
Snippets of useful code
private String searchQuery="";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null)
searchQuery = savedInstanceState.getString(Tag.SEARCH_QUERY);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(Tag.SEARCH_QUERY, searchQuery);
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater menuInflater) {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_search, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = null;
if (menuItem != null)
searchView = (SearchView) menuItem.getActionView();
if (searchView != null) {
searchView.setQuery(searchQuery,false);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//searching is done in async task
searchQuery = query;
NetworkUtility.onProgressBarShow(getActivity());
MyAsyncTaskDownloadDetails myAsyncTaskDownloadDetails = new MyAsyncTaskDownloadDetails();
myAsyncTaskDownloadDetails.execute(new String[]{Tag.PLP_URL + query, Tag.PLP,""});
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
}
super.onCreateOptionsMenu(menu, menuInflater);
}
}
First of all you are saving queryText in onQueryTextSubmit callback which means searchQuerywill remain empty unless and until user have submitted query for search, so keep that in mind.
Secondly try following code. It will work I have tested it.
if(searchQuery.length()>0){
//See this commented code
// if(Utils.hasIceCreamSandwich()) {
// searchMenuItem.expandActionView();
// }else {
// MenuItemCompat.expandActionView(searchMenuItem);
// }
MenuItemCompat.expandActionView(menuItem);
searchView.setQuery(searchQuery, false);
}

How to let SearchView keep its last query content after reopen?

When using search view, I have a requirement from customer that they want to retain the search content after reopen the search view. My Search view is on a list view and do a real timing filtering based on what user input into the search box. When closed the search box by either click the back button on the phone or click the soft back button on the top left on action bar, the search box closed, search view iconfied. But when reopen it next time, the search query used last time is also been cleared, which I do not want.
My question is that is there a way I can keep the search view content there. Just hiding the search box, but not clear the content?
My related code are as follow:
MenuItem search;
SearchView searchView;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_locationlist_fragment, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
search = menu.findItem(R.id.action_search_location_list);
searchView = (SearchView) MenuItemCompat.getActionView(search);
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(this);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
//This will make sure, when user closed search view, the list will be restored.
if(!hasFocus) {
Log.i(Tags.LOCATIONLIST,"Search Close");
search.collapseActionView();
} else {
}
}
}
});
ImageView closeButton = (ImageView)searchView.findViewById(R.id.search_close_btn);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchEditText = (EditText)searchView.findViewById(R.id.search_src_text);
searchEditText.setText("");
if (((LocationListAdapter)locationListView.getAdapter())!=null) {
((LocationListAdapter) locationListView.getAdapter()).getFilter().filter("");
}
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search_location_list:
((BaseActivity) getActivity()).onSearchRequested();
return true;
case R.id.action_refresh_location_list:
refreshLocationList();
return true;
default:
return false;
}
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (((LocationListAdapter)locationListView.getAdapter())!=null) {
if (TextUtils.isEmpty(s)) {
locationListView.clearTextFilter();
} else {
((LocationListAdapter) locationListView.getAdapter()).getFilter().filter(s);
//locationListView.setFilterText(s.toString());
}
}
return true;
}
Use
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setIconified(false);
Any query text is cleared when iconified. So setIconified to false. And i have used android.widget.SearchView
Save your String in a variable (e.g. myWantedString) and
override setOnClickListener that trigers everytime you open the SearchView and use setQuery. Your code should be:
searchView.setOnSearchClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
searchView.setQuery(myWantedString, false);
}
});
To save your string each time the SearchView closes implement setOnCloseListener and override onClose():
searchView.setOnCloseListener(new SearchView.OnCloseListener()
{
#Override
public boolean onClose()
{
myWantedString = searchView.getQuery();
return false;
}
});
searchView.setQuery() works if was called with a delay after menu item expansion.
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
// set query text with a delay
searchView.post(new Runnable() {
#Override
public void run() {
searchView.setQuery(query, false);
}
});
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return true;
}
});
You can create an Activity which can be called when the user searches and the search result can be stored in the Bundle during the callback method onPause or onSaveInstanceState , when the Activity is called once again restore it from the bundle.
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setIconified(false);
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchView.setQuery("SEARCH_WORD", false);
}
});
https://developer.android.com/reference/android/widget/SearchView
Sets a listener to inform when the search button is pressed. This is only relevant when the text field is not visible by default. Calling setIconified(false) can also cause this listener to be informed.

How to implement search widget in Action Bar Sherlock?

I tried to get Search box to work on Action Bar Sherlock.
This is my PreLocationActivity:
#ContentView(R.layout.search)
public class PreLocationActivity extends RoboSherlockActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.map_layout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Used to put dark icons on light action bar
menu.add("Search")
.setIcon(R.drawable.ic_search_inverse)
.setActionView(R.layout.collapsible_edittext)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return true;
}
#Override
public boolean onSearchRequested() {
return super.onSearchRequested();
}
}
This is my SearchableActivity:
#ContentView(R.layout.search)
public class SearchableActivity extends RoboSherlockFragmentActivity {
#InjectView(R.id.addressListView) ListView addressView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doGeoSearch(query);
}
}
public void doGeoSearch(String query){
Geocoder geocoder;
ArrayList<Address> addresses;
ArrayList<String> address = new ArrayList<String>() ;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = (ArrayList<Address>) geocoder.getFromLocationName(query, 6);
Log.d("Address",String.valueOf(addresses));
for(int i = 0;i<addresses.size();i++)
{
String addr = new String();
addr.concat(addresses.get(i).getAddressLine(0));
addr.concat(addresses.get(i).getAddressLine(1));
addr = addresses.get(i).getAddressLine(0) + addresses.get(i).getLocality() + addresses.get(i).getAdminArea();
//addr.concat(addresses.get(i).getAddressLine(2));
Log.d("addr",addr);
address.add(addr);
}
SearchAddressAdapater addressList = new SearchAddressAdapater(getApplicationContext(),R.layout.search_list,addresses, SearchableActivity.this);
addressView.setAdapter(addressList);
//ListView addressListView = new ListView();
} catch (IOException e) {
//Handle exception
}
}
No success at all. As in, when I type something on the Prelocation Activity and press enter, nothing is being searched. Do I have to treat it as an EditText and write a text listener for that which then calls the geoCoder and gets me the locations or is there a smarter way to go about it?
Android Support Library(v4 + v7):
Support Library v7: http://developer.android.com/tools/support-library/features.html#v7-appcompat
Google now supports the ActionBar compatibility back to Android 2.1(API 7).
It is easy to make the transition because the method names are the same and/or very similar.
Add the Support Library with Resources: http://developer.android.com/tools/support-library/setup.html#libs-with-res
Your Manifest: AndroidManifest.xml
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
Your Menu: menu.xml
<item
android:id="#+id/menu_search"
android:actionViewClass="android.support.v7.widget.SearchView"
android:icon="#drawable/ic_action_search"
android:showAsAction="ifRoom|collapseActionView"
android:title="Search"/>
ActionBarSherlock [deprecated, use appcompat]:
Here is how to use the standard SearchView and SearchManager in Android with ActionBarSherlock! I am using this code and works fine. I have tested this on Android 2.3(API 10) - Android 4.3(API 18).
Great Tutorial and Documentation:
http://developer.samsung.com/android/technical-docs/UI-unification-with-older-Android-versions-using-ActionBarSherlock
Keep in mind:
Custom Search with ActionBarSherlock(min. API 7)
SearchView with ActionBarSherlock(min. API 8)
Your Menu: menu.xml
<item
android:id="#+id/menu_search"
android:actionViewClass="com.actionbarsherlock.widget.SearchView"
android:icon="#drawable/ic_action_search"
android:showAsAction="ifRoom|collapseActionView"
android:title="Search"/>
For Both:
Your Activity: MainActivity.java
public boolean onCreateOptionsMenu(Menu menu)
{
getSupportMenuInflater().inflate(R.menu.menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
if (null != searchView )
{
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener()
{
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
adapter.getFilter().filter(newText);
return true;
}
public boolean onQueryTextSubmit(String query)
{
// this is your adapter that will be filtered
adapter.getFilter().filter(query);
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
Let me know if this works for you as well and let me know if you need anymore help!
private EditText search;
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu)
{
menu.add(0, 1, 1, R.string.menu_search).setIcon(R.drawable.ic_action_search).setActionView(R.layout.action_search).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item)
{
switch (item.getItemId())
{
case 1:
search = (EditText) item.getActionView();
search.addTextChangedListener(filterTextWatcher);
search.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
private TextWatcher filterTextWatcher = new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// your search logic here
}
};
A similar question there are here where I had the problem to assign the adapter.
How to implement search widget with a listview using SherlockActionbar?
I hope that it would help because I had the same problem.
To use the adapter the best way is that the class implements SearchView.OnQueryTextListener and then you donĀ“t have to create the inner class and you will have the adapter.
In your code will be something as:
public class MainActivity extends SherlockListActivity implements SearchView.OnQueryTextListener
and then in the class you have to define the methods. The adapter will be the adapter that you have in your class ArrayAdapter adapter. But you should define it as private in the class.
public boolean onQueryTextChange(String newText) {
// this is your adapter that will be filtered
adapter.getFilter().filter(newText);
return true;
}
public boolean onQueryTextSubmit(String query) {
// this is your adapter that will be filtered
adapter.getFilter().filter(query);
return true;
}
In the line where you are setting:
searchView.setOnQueryTextListener(queryTextListener);
Should be:
searchView.setOnQueryTextListener(this);
If you have any problem let me know, I was with a similar problem today and read your question without answer.

Auto Collapse ActionBar SearchView on Soft Keyboard close

I am currently using an ActionBar menu item to display a SearchView in the action bar. When the search menu item is expanded the soft keyboard is displayed which is what I want. Now, when the user presses the back button to close the soft keyboard, I would also like to collapse the SearchView in the action bar.
I have tried implementing the following listeners OnKeyListener and OnFocusChangeListener on the MenuItem and the ActionView. I have also tried using OnBackPressed() in the Activity. None of the above detect when the back button is used to close the soft keyboard.
Any ideas?
I have implemented OnActionExpandListener to know when the SearchView is visible.
I'll expand on #user1258568 's answer for the lazy. This worked for me. Note that it clears your query when focus is lost.
final MenuItem searchMenuItem = optionsMenu.findItem(R.id.search);
final SearchView searchView = (SearchView) searchMenuItem.getActionView();
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean queryTextFocused) {
if(!queryTextFocused) {
searchMenuItem.collapseActionView();
searchView.setQuery("", false);
}
}
});
I found a better solution.
searchView.setOnQueryTextFocusChangeListener().
The OnQueryTextFocusChangeListener gets called when the keyboard is displayed or hidden. Gets called first when the keyboard is displayed and the search view will have focus. Gets called again when keyboard is hidden and search view will lose focus, can close search viewthen using
menuItem.collapseActionView().
Just Override onBackPressed like this:
#Override
public void onBackPressed() {
if (searchView.isShown()){
searchView.onActionViewCollapsed(); //collapse your ActionView
searchView.setQuery("",false); //clears your query without submit
isClosed = true; //needed to handle closed by back
} else{
super.onBackPressed();
}
}
and your onCreateOptionsMenu would inflate the mSearchView like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_search, menu);
mSearchView = (SearchView) menu.findItem(R.id.menu_action_search).getActionView();
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnSearchClickListener(this);
mSearchView.setOnCloseListener(this);
isClosed = true;
return true;
}
have you class implement the following like this:
public class myActivity extends FragmentActivity implements
SearchView.OnQueryTextListener, View.OnClickListener, SearchView.OnCloseListener {
which you will also need:
#Override
public void onClick(View view) {
isClosed = false;
}
#Override
public boolean onClose() {
isClosed = true;
return false;
}
You will need to make "mSearchView" and "isClosed" both global variables to the activity.
The answer from Jon Willis works great. This is an improvement to his answer.
First, create a new class that implements View.OnFocusChangeListener:
public class SearchViewFocusListener implements View.OnFocusChangeListener {
private final MenuItem mMenuItem;
public SearchViewFocusListener(MenuItem menuItem) {
mMenuItem = menuItem;
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
mMenuItem.collapseActionView();
if (v instanceof SearchView) {
((SearchView) v).setQuery("", false);
}
}
}
}
Next, set the listener on your SearchView:
searchView.setOnQueryTextFocusChangeListener(new SearchViewFocusListener(menuItem));
You only need to put the "collapseActionView" attribute in the menu layout
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_item_search"
android:title="#string/search"
android:iconifiedByDefault="true"
android:icon="#drawable/ic_action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"/> <--this one
</menu>
That will give you the functionality you look for all by itself.Don't forget to call the method "clearFocus" on the SearchView to close the keyboard once you send the query.
This is what I did for making the keyboard disappear. You can try to see if this works for you. I set the searchView to invisible and then to visible again.
//set query change listener
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
/**
* hides and then unhides search tab to make sure keyboard disappears when query is submitted
*/
searchView.setVisibility(View.INVISIBLE);
searchView.setVisibility(View.VISIBLE);
return false;
}
});
It's achievable like this:
private void setupSearchView(Menu menu) {
final MenuItem searchMenuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) searchMenuItem.getActionView();
[...]
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
searchMenuItem.collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
}
Solutions based on setOnQueryTextFocusChangeListener() did not work for me because the event was not launched - the searchView did not lose focus when submitted, probably because I perform the search in the same activity that contains the Search View.
Anyway, I think using OnQueryTextListener is more correct, as it describes the event of submitting text more precisely.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.home_screen, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final MenuItem searchMenuItem = menu.findItem(R.id.menu_search);
final SearchView searchView = (SearchView) searchMenuItem
.getActionView();
searchView.setIconifiedByDefault(false);
if (searchManager != null && searchView != null) {
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView
.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if (searchMenuItem != null) {
searchMenuItem.collapseActionView();
}// end if
if (searchView != null) {
searchView.setQuery("", false);
}// end if
}// end if
}
});
searchView
.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
/**
* hides and then unhides search tab to make sure
* keyboard disappears when query is submitted
*/
if (searchView != null) {
searchView.setVisibility(View.INVISIBLE);
searchView.setVisibility(View.VISIBLE);
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
});
}
return super.onCreateOptionsMenu(menu);
}
If you want to collapse keyboard when user clicks search icon on keyboard
this can be achieved by simple
inside onquerytextsubmitted {
searchView.clearfocus()
}
You need to call setIconified twice.
To actually collapse your search view and close the keyboard.
With first call text of search view is cleared with second call keyboard and search view get closed.
For some reason, menuItem.collapseActionView() did not work so I used searchView.setIconified(true) instead.
This gives the below result as the code sample.
final MenuItem searchItem = (MenuItem) menu.findItem(R.id.menu_item_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextFocusChangeListener(new SearchView.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
searchView.setIconified(true);
}
}
});

Categories

Resources