How to handle back arrow event in a SearchView

只愿长相守 提交于 2021-02-10 20:40:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!