知识点:菜单(menu)
步骤一、创建菜单项(核心代码如下)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//参数1:分组id
//参数2:菜单项id
//参数3:顺序
//参数4:菜单文字
MenuItem item1=menu.add(0, 0, 0, "菜单1");
item1.setIcon(R.drawable.ic_launcher);
item1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
MenuItem item2=menu.add(0, 1, 1, "菜单2");
item2.setIcon(R.drawable.ic_launcher);
item2.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
MenuItem item3=menu.add(0, 2, 2, "菜单3");
item3.setIcon(R.drawable.ic_launcher);
item3.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
MenuItem item4=menu.add(0, 3, 3, "菜单4");
item4.setIcon(R.drawable.ic_launcher);
item4.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
MenuItem item5=menu.add(0, 4, 4, "菜单5");
item5.setIcon(R.drawable.ic_launcher);
MenuItem item6=menu.add(0, 5, 5, "菜单6");
item6.setIcon(R.drawable.ic_launcher);
MenuItem item7=menu.add(0, 6, 6, "菜单5");
item7.setIcon(R.drawable.ic_launcher);
MenuItem item8=menu.add(0, 7, 7, "菜单6");
item8.setIcon(R.drawable.ic_launcher);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
步骤二、菜单项被选中事件)(核心代码如下)
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case 0:
Toast.makeText(this, "菜单1", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(this, "菜单2", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(this, "菜单3", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(this, "菜单4", Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(this, "菜单5", Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(this, "菜单6", Toast.LENGTH_SHORT).show();
break;
case android.R.id.home:
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
源码下载请点击这里: