三类:
Options Menu
Context Menu
Sub Menu
1.Options Menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, 1, 1, "苹果");
menu.add(0, 2, 2, "香蕉");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case 1:
Toast.makeText(this, "你选的是苹果", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(this, "你选的是香蕉", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}<span style="color:#366092;">
</span>
2.Context Menu
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contextmenu);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
registerForContextMenu(btn1);
registerForContextMenu(btn2);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
if (v == btn1) {
menu.setHeaderTitle("这是1");
menu.add(200, 200, 200, "Context Menu 1");
menu.add(200, 201, 201, "Context Menu 2");
} else if (v == btn2) {
menu.setHeaderTitle("这是2");
menu.add(300, 300, 300, "C 1");
menu.add(300, 301, 301, "C 2");
}
super.onCreateContextMenu(menu, v, menuInfo);
}
3.Sub Menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, 1, 1, "苹果");
menu.add(0, 2, 2, "香蕉");
SubMenu subMenu = menu.addSubMenu(1, 100, 100, "桃子");
subMenu.add(2, 101, 101, "大桃子");
subMenu.add(2, 102, 102, "小桃子");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case 1:
Toast.makeText(this, "你选的是苹果", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(this, "你选的是香蕉", Toast.LENGTH_SHORT).show();
break;
case 101:
Toast.makeText(this, "大桃子", Toast.LENGTH_SHORT).show();
break;
case 102:
Toast.makeText(this, "小桃子", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);