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); } }
在res文件夹下,values文件下的Strings.xml
<?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>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。