1. 范例说明
- 该范例介绍Android Menu Key的设计,并示范“关于”对话框、“离开程序”等语法。
- 程序里除了默认重写onCreate()之外,还需要另外新建两个类函数:onCreateOptionsMenu()和onOptionsItemSelected()。前者为创建Menu菜单的项目,后者则是处理菜单被选择运行后的事件处理,最后则是在当User单击“关于”菜单之后,弹跳出AlertDialog,以显示这个程序的“关于”信息。
2. 运行结果

3. 编写代码
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, R.string.app_about);
menu.add(0, 1, 1, R.string.str_exit);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
// case 0:
case R.id.new_game:
openOptionsDialog();
break;
// case 1:
case R.id.help:
finish();
break;
}
return true;
}
4. 扩展学习与作业
1.Options Menu(选项菜单) 的简单使用
http://www.eyeandroid.com/thread-9787-1-1.html
2.MenuInflater
http://www.eyeandroid.com/thread-9810-1-1.html
3.onPrepareOptionsMenu和onCreateOptionsMenu的区别
http://www.eyeandroid.com/thread-9811-1-1.html
作业:写一个例子使用在XML中定义的Menu
视频讲解:http://www.eyeandroid.com/thread-9845-1-1.html
浙公网安备 33010602011771号