All we need is an easy explanation of the problem, so here it is.
In my application I am using the Action Bar with a custom SearchView in it. I want to use some custom code when the user hits the enter button in the search field. But I cant find a way to catch the moment the user hits the enter button in the SearchView.
Now I tried several ways to capture the search action but I cant seem to find it.
My button is defined like this:
<item
android:id="@+id/action_bar_search"
android:title="Search"
android:icon="@drawable/ic_menu_search"
android:showAsAction="always"
android:actionViewClass="-package-.CustomSearchView"
/>
With this belongs the CustomSearchView class:
public class CustomSearchView extends SearchView implements OnClickListener, android.view.View.OnKeyListener{
public CustomSearchView(Context context) {
super(context);
this.setOnSearchClickListener(this);
this.setSubmitButtonEnabled(true);
this.setOnClickListener(this);
this.setOnKeyListener(this);
}
@Override
public void onClick(View v) {
Log.d("SEARCH", "Onclick! " + this.getQuery());
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
Log.d("SEARCH", "Search onkey");
return false;
}
}
Here you can see that I`ve tried 2 approaches:
- Catch the onclick event from the submit button. That didnt work
since it only fired when I clicked on the search icon to open the
SearchView. - Catch keystrokes within the SearchView. That didnt work
either. Got no response from any key that I pressed there.
Does anyone have a way of making a custom Search action with this SearchView?
UPDATE:
As stated below by PJL: You dont need a custom dialog for overriding this behaviour. The normal SearchView widget will work just fine for this.
How to solve :
I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.
Method 1
Get your search view and add an OnQueryTextListener
final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
// Do something
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// Do something
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
By the way my menu layout is as follows;
<item android:id="@+id/menu_search"
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView" />
Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0