首页 > 代码库 > 一起学android之磨刀不误砍柴工(6)

一起学android之磨刀不误砍柴工(6)

菜单包括选项菜单(OptionMenu)、上下文菜单(ContextMenu)、子菜单(SubMenu).

创建子菜单(SubMenu)的步骤:

1、重写Activity的onCreateOptionMenu(Menu menu)的方法,在此方法中通过Menu对象的方法添加菜单。


2、响应菜单的单击事件,重写Activity的onOptionItemSelected(MenuItem mi)方法


代码如下:

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//创建子菜单
		SubMenu subMenu1=menu.addSubMenu("子菜单1");
		//设置菜单头的标题
		subMenu1.setHeaderTitle("菜单头的标题1");
		//设置菜单的图标
		subMenu1.setIcon(R.drawable.ic_launcher);
		//设置菜单头的图标
		subMenu1.setHeaderIcon(R.drawable.ic_launcher);
		//向0组中添加菜单项
		subMenu1.add(0, 0, 0, "菜单项1");
		subMenu1.add(0, 1, 0, "菜单项2");
		subMenu1.add(0, 2, 0, "菜单项3");
		
		return true;
	}
	   @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		toast(item.getTitle());
		return super.onOptionsItemSelected(item);
	}

	private void toast(CharSequence title) {
		// TODO Auto-generated method stub
		Toast.makeText(MainActivity.this,title, Toast.LENGTH_SHORT).show();
	}

}

效果图

点击Menu时:



单击子菜单1:


一起学android之磨刀不误砍柴工(6)