标签:android 菜单 optionmenu
1.选项菜单(optionMenu)
创建选项菜单的步骤:
1.覆盖Activity的 onCreateOptionMenu(Menu menu)方法,当菜单第一次被打开时调用
2.调用Menu的add() 方法添加菜单项(MenuItem),同时可以调用MenuItem的setlcon()方法为菜单项设置图标
3.当菜单项(MenuItem)被选择是,覆盖Activity 的onOptionsItemSelected(MenuItem item)来响应事件
import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.widget.Toast; public class MainActivity extends Activity { private static final int SET_ITEM1=Menu.FIRST+2; private static final int SET_ITEM2=Menu.FIRST+3; private static final int SET_ITEM3=Menu.FIRST+4; private static final int SET_ITEM4=Menu.FIRST+5; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //填充选项菜单(读取xml文件,解析,加载到Menu组件上) @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); //添加子菜单 SubMenu sub1=menu.addSubMenu("设置"); sub1.add(1,SET_ITEM1,300,"设置声音"); sub1.add(1,SET_ITEM2,400,"设置桌面"); SubMenu sub2=menu.addSubMenu("选择"); sub2.add(1,SET_ITEM3,300,"选择一"); sub2.add(1,SET_ITEM4,400,"选择二"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.start: Toast.makeText(this, "开始游戏", Toast.LENGTH_SHORT).show(); break; case R.id.over: Toast.makeText(this, "结束游戏", Toast.LENGTH_SHORT).show(); break; case SET_ITEM1: Toast.makeText(this,"声音设置" , Toast.LENGTH_SHORT).show(); break; case SET_ITEM2: Toast.makeText(this, "桌面设置", Toast.LENGTH_SHORT).show(); break; case SET_ITEM3: Toast.makeText(this, "选择一", Toast.LENGTH_SHORT).show(); break; case SET_ITEM4: Toast.makeText(this, "选择二", Toast.LENGTH_SHORT).show(); break; default: break; } return super.onOptionsItemSelected(item); } }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">游戏</string> <string name="start">开始</string> <string name="over">结束</string> <string name="hello_world">你好世界!</string> <string name="contextTitle">上下文菜单</string> </resources>
标签:android 菜单 optionmenu
原文地址:http://blog.csdn.net/u013238646/article/details/46418663