Android – SearchView: Adding a Search component direct on your APP menu.
A SearchView is
View (GUI Component) to be displayed in the toolbar, which user can enter a
text for searching anything within your APP.
Of course, programmatically
we can Interact with SeachView to identify the its interaction with the user
and the inputted values. However the whole search behavior has to be
implemented by each application.
In this tutorial
we are going to see how to include a SearchView in your APP toolbar, and how to
handle its events.
The SearchView is
defined in any layout for menus, and its is like a normal menu item. However it
has different behavior because of the attributes app:actionViewClass
and app:showAsAction
as we can see in
the code below:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/app_bar_search"
android:icon="@drawable/ic_search_black_24dp"
android:title="Search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always|collapseActionView" />
</menu>
Then in the Activity we want to employ
this menu, in the method onCreateOptionsMenu it is necessary to instantiate and
assign a SearchView.OnQueryTextListener object, because this
object that will introduce a custom behavior to this View object, otherwise, it
will be just a inanimate element in user interface.
@Override
public
boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
// Associate searchable
configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.app_bar_search).getActionView();
searchView.setSearchableInfo( searchManager.getSearchableInfo(getComponentName()));
final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
((TextView)findViewById(R.id.textViewSearchViewText)).setText(newText);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
((TextView)findViewById(R.id.textViewSearchViewText)).setText(query.toUpperCase());
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return true;
}
Here there is two important methods to
be overwritten, the onQueryTextChange which is going to be
triggered every inputted char, and the onQueryTextSubmit that will be triggered just When user concludes
its typing, normally pressing the Lupe button. Depending of what are you
developing you can choose to introduce behavior to both methods or just a
single one.
You can watch a video class about this topic below:
Comments
Post a Comment