How to detect SearchView's back button press?

后端 未结 5 1419
故里飘歌
故里飘歌 2021-02-18 16:39

I\'m using a single activity to display SearchView as well as to display search results. The search results is just a subset of items so the search acts as a filter. Everythin

5条回答
  •  我寻月下人不归
    2021-02-18 17:10

    Darwind's answer will do the job but that only works when user presses the back button to close the keyboard and when SearchView doesn't have focus anymore.

    The better way to do it is to listen for SearchView's text changes.
    This way you can restore views and control UI as the text is updating.
    here's how I do it.

    SearchView searchView = new SearchView(context);
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            // this is when user is done typing and clicks search
            return false;
        }
    
        @Override
        public boolean onQueryTextChange(String newText) {
            // you can use this to do a "live" search while the user is typing.
            // this will trigger each time user changes (adds or removes) text
            // so when newText is empty, restore your views
            return false;
        }
    });
    

提交回复
热议问题