显示选项菜单

作者:追风剑情 发布于:2015-9-23 21:46 分类:Android

代码

package com.example.androidtest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MenusActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_menus);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		CreateMenu(menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		return MenuChoice(item);
	}
	
	private void CreateMenu(Menu menu)
	{
		//add(菜单项所在的组的标识符(使用0表示一个菜单项不在一个组中),
		//唯一的菜单项ID,菜单项显示顺序,菜单项显示的文本)
		MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");
		{
			mnu1.setAlphabeticShortcut('a');//给菜单项分配快捷键
			mnu1.setIcon(R.drawable.ic_launcher);//菜单项上显示的图像
		}
		MenuItem mnu2 = menu.add(0, 1, 1, "Item 2");
		{
			mnu2.setAlphabeticShortcut('b');
			mnu2.setIcon(R.drawable.ic_launcher);
		}
		MenuItem mnu3 = menu.add(0, 2, 2, "Item 3");
		{
			mnu3.setAlphabeticShortcut('c');
			mnu3.setIcon(R.drawable.ic_launcher);
		}
		MenuItem mnu4 = menu.add(0, 3, 3, "Item 4");
		{
			mnu2.setAlphabeticShortcut('d');
		}
		menu.add(0, 4, 4, "Item 5");
		menu.add(0, 5, 5, "Item 6");
		menu.add(0, 6, 6, "Item 7");
	}
	
	private boolean MenuChoice(MenuItem item)
	{
		switch(item.getItemId())
		{
		case 0:
			Toast.makeText(this, "You clicked on Item 1", 
					Toast.LENGTH_SHORT).show();
			return true;
		case 1:
			Toast.makeText(this, "You clicked on Item 2", 
					Toast.LENGTH_SHORT).show();
			return true;
		case 2:
			Toast.makeText(this, "You clicked on Item 3", 
					Toast.LENGTH_SHORT).show();
			return true;
		case 3:
			Toast.makeText(this, "You clicked on Item 4", 
					Toast.LENGTH_SHORT).show();
			return true;
		case 4:
			Toast.makeText(this, "You clicked on Item 5", 
					Toast.LENGTH_SHORT).show();
			return true;
		case 5:
			Toast.makeText(this, "You clicked on Item 6", 
					Toast.LENGTH_SHORT).show();
			return true;
		case 6:
			Toast.makeText(this, "You clicked on Item 7", 
					Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}
}

运行效果

mmm.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号