How do I close a SearchView programmatically?

后端 未结 13 1746
误落风尘
误落风尘 2020-12-23 19:10

I currently have a SearchView in the action bar of my app. When I click the search icon, the SearchView expands and the keyboard pops up as expecte

13条回答
  •  一个人的身影
    2020-12-23 19:13

    My way:

    1. Create CustomSearchView class
    
        public class CustomSearchView extends SearchView{
            public CustomSearchView(final Context context) {
                super(context);
                this.setIconifiedByDefault(true);
            }
    
            @Override
            public boolean dispatchKeyEventPreIme(KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && 
                    event.getAction() == KeyEvent.ACTION_UP) {
                    this.onActionViewCollapsed();
                }
                return super.dispatchKeyEventPreIme(event);
            }
        }
    
    
    1. Add actionViewClass
        
    
    1. Create CustomSearchView into onCreateOptionsMenu
        CustomSearchView searchView = (CustomSearchView)menu.findItem(R.id.menu_search).getActionView();
    

提交回复
热议问题