MaterialSearchView搜索框

1.添加依赖

implementation 'com.miguelcatalan:materialsearchview:1.4.0'

2.布局



            

            
        

3.创建选项菜单以及解绑

    @Override
    public void onBackPressed() {
        if (mSearchView.isSearchOpen()) {
            mSearchView.closeSearch();
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.item, menu);
        mSearchViewItem = menu.findItem(R.id.action_search);
        //隐藏menu,搜索框就不见了,想要搜索框不见只能使用mSearchViewItem
        mSearchViewItem.setVisible(false);
        mSearchView.setMenuItem(mSearchViewItem);
        return super.onCreateOptionsMenu(menu);
    }

4.获取控件结束后监听事件

        MaterialSearchView mSearchView = (MaterialSearchView) findViewById(R.id.search_view);
        mSearchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                //Do some magic
                //点击搜索按钮提交搜索的内容
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //Do some magic
                //搜索框中内容发生改变
                return false;
            }
        });

        mSearchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
            @Override
            public void onSearchViewShown() {
                //Do some magic
                //搜索框展开
            }

            @Override
            public void onSearchViewClosed() {
                //Do some magic
                //搜索框折叠
            }
        });

你可能感兴趣的:(MaterialSearchView搜索框)