码迷,mamicode.com
首页 > 移动开发 > 详细

android基础学习 菜单optionMenu

时间:2015-06-09 10:03:42      阅读:134      评论:0      收藏:0      [点我收藏+]

标签: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>


android基础学习 菜单optionMenu

标签:android   菜单   optionmenu   

原文地址:http://blog.csdn.net/u013238646/article/details/46418663

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!