问题
How can I handle the click event on the back arrow in the searchview widget:
I tried this code but it doesn't work:
searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "back arrow clicked");
}
});
also I tried this one:
MenuItemCompat.setOnActionExpandListener(item_search, new
MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
return true;
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true;
}
});
The problem with the above code is that calling onMenuItemActionCollapse() method also executes onQueryTextChange() which is undesirable.
So some help please.
回答1:
To handle that you have to override onOptionsItemSelected
method.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
// handle back event.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
来源:https://stackoverflow.com/questions/45635482/how-to-handle-back-arrow-event-in-a-searchview