使用菜单需要重写两个类:onCreateOptionsMenu()和onOptionsItemSeleted()
public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.menu,menu); //getMenuInflater返回一个MenuInflater对象 //r.menu.menu为菜单资源文件,menu为装载资源文件的对象 return true; //返回true,让菜单显示出来 } //响应事件 public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.add_item: Toast.makeText(MainActivity.this, "You clicked Add ", Toast.LENGTH_SHORT).show(); break; case R.id.remote_item: Toast.makeText(MainActivity.this,"You clicked Remote",Toast.LENGTH_SHORT).show(); break; default: } return true; }
同时新建菜单资源文件:
<menu> <item android:id="@+id/add_item" android:title="Add"/> <item android:id="@+id/remote_item" android:title="remote"/> </menu>