SearchBar中的SearchView

时间:2015-07-21 13:20:27

标签: android searchview

我已按照this代码在SearchView内实施ActionBar(作为菜单中的项目)。

但是当我到达这条线时

mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

getActionView()返回null值。

我无法弄清楚出了什么问题。

2 个答案:

答案 0 :(得分:2)

尝试替换

mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

mSearchMenuItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(mSearchMenuItem);

答案 1 :(得分:0)

试试这个..

private SearchView mSearchView;

....
....

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
             // Inflate the menu items for use in the action bar
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.activity, menu);

            MenuItem searchItem = menu.findItem(R.id.action_search);
            mSearchView = (SearchView) searchItem.getActionView();
            setupSearchView(searchItem);

            return super.onCreateOptionsMenu(menu);
        }

        private void setupSearchView(MenuItem searchItem) {

            if (isAlwaysExpanded()) {
                mSearchView.setIconifiedByDefault(false);
            } else {
                searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
                        | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
            }

            mSearchView.setOnQueryTextListener(this);
         }

         public boolean onQueryTextChange(String newText) {

                //Query

                return false;
         }

         public boolean onQueryTextSubmit(String query) {

                //query

                return false;
         }

         public boolean onClose() {
                return false;
         }

         protected boolean isAlwaysExpanded() {
                return false;
         }

不要忘记实施搜索查看...

implements SearchView.OnQueryTextListener