0

我有以下代码,并且 onOptionItemSelected() 永远不会运行。它永远不会到达Log.i("", "switch"); 任何人都知道为什么?

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.category_menu, menu);
        Log.i("", "created menu");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.i("", "switch");
        switch (item.getItemId()) {
        case 0:
            Log.i("", "case 0");
            search = (EditText) item.getActionView();
            search.addTextChangedListener(filterTextWatcher);
            search.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

        }
        return true;
    }

    private TextWatcher filterTextWatcher = new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            Log.d("", "my search logic");
        }

    };
4

2 回答 2

1

也许你想要更好的这样的东西。SearchView 已经有一个侦听器来处理查询。

在 onCreateOptionsMenu(菜单菜单):

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);

    MenuItem searchItem = menu.findItem(R.id.action_search);
    mSearchView = (SearchView) searchItem.getActionView();
    mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            Log.w("SEARCH","Search: "+s);
            startSearch(s,true,null,true);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            Log.w("SEARCH","Typing: "+s);
            return false;
        }
    });
于 2015-05-14T14:05:08.537 回答
0

你真的有任何菜单项category_menu吗?onOptionsItemSelected当菜单中的一个项目被触摸时被调用,而不仅仅是在菜单本身被打开时。如果您确实有菜单项,请触摸其中一项,然后在 LogCat 中您应该会看到“切换”日志语句。

于 2012-11-17T22:18:16.820 回答