Reputation: 7107
I have implemented the Android search widget
in my navigation drawer
based app. I have set it to open the keyboard and focus the editText
when clicking on the search icon. I want to set the back button (up button) to hide the keyboard. I have searched the web for the R.id
of the up button, and found this android.R.id.home
. So I have set it to be:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
...
case android.R.id.home:
hideKeyboard();
break;
...
}
I debugged the code and noticed that clicking on the navigation bar
icon fires up the android.R.id.home
, but hitting the up button of the search widget doesn't even enter the onOptionsItemSelected(MenuItem item)
function.
I have also tried this:
searchView.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard();
}
}
});
But didn't work.
How can I hide the keyboard when pressing the back (up) button?
Setting the search view:
private void setSearchView(Menu menu) {
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
Home.getFilter().filter(newText);
return true;
}
public boolean onQueryTextSubmit(String query) {
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
}
Upvotes: 6
Views: 768
Reputation: 702
The following code should work:
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setOnCloseListener(new OnCloseListener() {
@Override
public bool OnClose() {
searchView.clearFocus();
return true;
});
However this didn't work for me for some reason. :-/
I found the workaround below here:
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
@Override
public void onViewDetachedFromWindow(View v) {
searchView.clearFocus();
}
@Override
public void onViewAttachedToWindow(View v) {
}
});
I don't think that using android.R.id.home
will work since I think that onOptionsItemSelected(android.R.id.home)
will only be called once the SearchView has been closed.
Upvotes: 2