how to handle back button of Search View in android

前端 未结 4 1257
刺人心
刺人心 2021-02-19 13:24
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(Menus.SEARCH));
searchView.setQueryHint(this.getString(R.string.search));
editSearch = (E         


        
相关标签:
4条回答
  • 2021-02-19 13:27

    If you are using search dialog you can do something like this for Kotlin

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
    
        return if (id == R.id.search_button) {
            val searchManager = this.getSystemService(Context.SEARCH_SERVICE) as SearchManager
            searchManager.setOnDismissListener {
                // return the activity to the normal state
            }
            // set activity to search state then request search
            onSearchRequested()
        } else super.onOptionsItemSelected(item)
    
    }
    
    0 讨论(0)
  • 2021-02-19 13:29

    MenuItemCompat.setOnActionExpandListener is now deprecated

    use

    menu.findItem(R.id.action_search)setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem menuItem) {
            return false;
        }
    
        @Override
        public boolean onMenuItemActionCollapse(MenuItem menuItem) {
            return false;
        }
    });
    

    instead

    0 讨论(0)
  • 2021-02-19 13:41

    Here is a way of doing it -

    @Override
    public void onBackPressed() {
    
        // Write your code here
    
        super.onBackPressed();
    }
    
    0 讨论(0)
  • 2021-02-19 13:46

    If you use android.support.v7.widget.SearchView as menu item:

    <menu
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <item
            android:id="@+id/action_search"
            android:title=""
            app:showAsAction="ifRoom|collapseActionView"
            app:actionViewClass="android.support.v7.widget.SearchView"/>
    </menu>
    

    You can handle back button (for expanded state) with:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        searchItem.expandActionView();
        MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                return true;
            }
    
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                // Write your code here
                return true;
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题