我刚试过这段代码:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.action_search:
MenuItemCompat.setOnActionExpandListener(item.findItem(R.id.action_search),
new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
System.out.println("expand");
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
System.out.println("collapse");
return true;
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}
但是它显示了一个错误,说:
无法解析方法" findItem(int)"
我检查了android developer,该方法似乎与我使用它的方式一样有效。 有谁知道它为什么不起作用? 感谢
答案 0 :(得分:4)
文档称它应该被称为菜单
item.findItem(R.id.action_search) // Here item is MenuItem not Menu
答案 1 :(得分:0)
试试这种方式
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.action_search:
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
System.out.println("expand");
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
System.out.println("collapse");
return true;
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}