我有以下代码,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");
}
};
答案 0 :(得分: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;
}
});
答案 1 :(得分:0)
你真的在category_menu
中有任何菜单项吗?触摸菜单中的项目时会调用onOptionsItemSelected
,而不仅仅是在打开菜单本身时。如果你有菜单项,请触摸一个,然后在LogCat中你应该看到你的"开关"日志声明。