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:
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.
just do your own search view, it is very simple. you then can include this layout in your activity layout file. This is a simple layout which includes a "search icon" followed by EditText, followed by "clear icon". The clear icon is shown after user types some text.
Add the Search View to the App Bar To add a SearchView widget to the app bar, create a file named res/menu/options_menu. xml in your project and add the following code to the file. This code defines how to create the search item, such as the icon to use and the title of the item.
You can use setQuery() to change the text in the textbox. However, setQuery() method triggers the focus state of a search view, so a keyboard will show on the screen after this method has been invoked. To fix this problem, just call searchView.
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" />
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