//onCreateOptionsMenu()创建选项菜单
--设置菜单项可用代码动态设置menu.add();
--通过xml设置MenuInflater.inflate()
// onOptionsItemSelected(MenuItem item)设置菜单点击事件
- 通过xml设置MenuInflater.inflate()
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item1:
Toast.makeText(MainActivity.this, "点击菜单一",Toast.LENGTH_SHORT).show();
break;
case R.id.menu_item2:
Toast.makeText(MainActivity.this, "点击菜单二",Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
menu目录下:
main.xml文件
<item
android:id="@+id/menu_item1"
android:orderInCategory="100"
android:showAsAction="never"
android:title="菜单一"/>
<item
android:id="@+id/menu_item2"
android:orderInCategory="100"
android:showAsAction="never"
android:title="菜单二"/>
- 通过xml设置MenuInflater.inflate()
public boolean onCreateOptionsMenu(Menu menu) {
//menu.add(groupId, itemId, order, title)
menu.add(1, 101, 1,"菜单一");
menu.add(1, 102, 1,"菜单二");
menu.add(1, 103, 1,"菜单三");
menu.add(1, 104, 1,"菜单四");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
/*switch (item.getItemId()) {
case R.id.menu_item1:
Toast.makeText(MainActivity.this, "点击菜单一",Toast.LENGTH_SHORT).show();
break;
case R.id.menu_item2:
Toast.makeText(MainActivity.this, "点击菜单二",Toast.LENGTH_SHORT).show();
break;
}*/
switch (item.getItemId()) {
case 103:
Toast.makeText(MainActivity.this, "点击菜单三",Toast.LENGTH_SHORT).show();
break;
case 101:
Toast.makeText(MainActivity.this, "点击菜单一",Toast.LENGTH_SHORT).show();
break;
case 102:
Toast.makeText(MainActivity.this, "点击菜单二",Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
如要实现某选项跳转功能---修改代码:
case 101:
Intent intent=new Intent(MainActivity.this, SecondActivity.class);
item.setIntent(intent);