Android 系统菜单与自定义菜单

Android 系统菜单与自定义菜单实现方法如下:系统菜单显示DefaultMenu.java

package com.wxz.menu;

import com.wxz.menu.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DefaultMenu extends Activity {
	private Button btnCustomizeMenu;
	private TextView tvTip;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.setTitle("Android 系统菜单");
	  btnCustomizeMenu = (Button)findViewById(R.id.btnCustomizeMenu);
	  btnCustomizeMenu.setOnClickListener(new ClickEvent());
	  tvTip = (TextView)findViewById(R.id.tvTip);
	  tvTip.setText("请按Menu键(F2)显示系统菜单");
	}
	 class ClickEvent implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(v==btnCustomizeMenu){
				Intent it = new Intent();
				it.setClass(DefaultMenu.this, CustomizeMenu.class);
				startActivity(it);
			}
		}
		 
	 }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		/*
		 * 
		 * add()方法的四个参数,依次是:
		 * 
		 * 1、组别,如果不分组的话就写Menu.NONE,
		 * 
		 * 2、Id,这个很重要,Android根据这个Id来确定不同的菜单
		 * 
		 * 3、顺序,那个菜单现在在前面由这个参数的大小决定
		 * 
		 * 4、文本,菜单的显示文本
		 */

		menu.add(Menu.NONE, Menu.FIRST + 1, 2, "删除").setIcon(

		android.R.drawable.ic_menu_delete);

		// setIcon()方法为菜单设置图标,这里使用的是系统自带的图标,以

		// android.R开头的资源是系统提供的,我们自己提供的资源是以R开头的

		menu.add(Menu.NONE, Menu.FIRST + 2, 3, "保存").setIcon(

		android.R.drawable.ic_menu_edit);

		menu.add(Menu.NONE, Menu.FIRST + 3, 4, "帮助").setIcon(

		android.R.drawable.ic_menu_help);

		menu.add(Menu.NONE, Menu.FIRST + 4, 1, "添加").setIcon(

		android.R.drawable.ic_menu_add);
        //返回true则显示,返回false则不显示
	    return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case Menu.FIRST + 1:

			Toast.makeText(this, "删除菜单被点击了", Toast.LENGTH_LONG).show();

			break;

		case Menu.FIRST + 2:

			Toast.makeText(this, "保存菜单被点击了", Toast.LENGTH_LONG).show();

			break;

		case Menu.FIRST + 3:

			Toast.makeText(this, "帮助菜单被点击了", Toast.LENGTH_LONG).show();

			break;

		case Menu.FIRST + 4:

			Toast.makeText(this, "添加菜单被点击了", Toast.LENGTH_LONG).show();

			break;

	   }
        // 返回false则正常显示,返回true则被消费掉
		return false;

	}

	@Override
	public void onOptionsMenuClosed(Menu menu) {
		Toast.makeText(this, "选项菜单关闭了", Toast.LENGTH_LONG).show();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		Toast.makeText(this,
				"选项菜单显示之前onPrepareOptionsMenu方法会被调用,你可以用此方法来根据打当时的情况调整菜单",
				Toast.LENGTH_LONG).show();

		// 如果返回false,此方法就把用户点击menu的动作给消费了,onCreateOptionsMenu方法将不会被调用

		return true;

	}
}

自定义菜单显示CustomizeMenu.java

package com.wxz.menu;

import java.util.ArrayList;
import java.util.HashMap;

import com.wxz.menu.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class CustomizeMenu extends Activity {
	private Button btnCustomizeMenu;
	private Button btnDefaultMenu;
	private TextView tvTip;
	private Context mContext;
	private boolean isMore = true;// menu菜单翻页控制
	AlertDialog menuDialog;// menu菜单Dialog
	GridView menuGrid;
	View menuView;

	// 菜单图片
	int[] menu_image_array = { R.drawable.menu_search,
			R.drawable.menu_bookmark, R.drawable.menu_bookmark_sync_import,
			R.drawable.menu_sharepage, R.drawable.menu_quit,
			R.drawable.menu_nightmode, R.drawable.menu_refresh,
			R.drawable.menu_more };
	// 菜单文字 
	String[] menu_name_array = { "搜索", "书签", "加入书签", "分享页面", "退出", "夜间模式",
			"刷新", "更多" };
	// 菜单图片2 
	int[] menu_image_array2 = { R.drawable.menu_auto_landscape,
			R.drawable.menu_checkupdate, R.drawable.menu_checknet,
			R.drawable.menu_refreshtimer, R.drawable.menu_syssettings,
			R.drawable.menu_help, R.drawable.menu_about, R.drawable.menu_return };
	// 菜单文字2 
	String[] menu_name_array2 = { "自动横屏", "检查更新", "检查网络", "定时刷新", "设置", "帮助",
			"关于", "返回" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mContext = CustomizeMenu.this;
		this.setTitle("Android 自定义菜单");
		btnCustomizeMenu = (Button) findViewById(R.id.btnCustomizeMenu);
		btnCustomizeMenu.setVisibility(View.GONE);

		btnDefaultMenu = (Button) findViewById(R.id.btnDefaultMenu);
		btnDefaultMenu.setVisibility(View.VISIBLE);
		btnDefaultMenu.setOnClickListener(new ClickEvent());

		tvTip = (TextView) findViewById(R.id.tvTip);
		tvTip.setText("请按Menu键(F2)显示自定义菜单");

		menuView = View.inflate(this, R.layout.gridview_menu, null);
		// 创建AlertDialog
		menuDialog = new AlertDialog.Builder(this).create();
		menuDialog.setView(menuView);
		menuDialog.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_MENU)// 监听按键
					dialog.dismiss();
				return false;
			}
		});

		menuGrid = (GridView) menuView.findViewById(R.id.gridview);
		menuGrid.setAdapter(getMenuAdapter(menu_name_array, menu_image_array));
		/** 监听menu选项 **/
		menuGrid.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {

				case 0:// 搜索,自动横屏
					if (isMore)
						Toast.makeText(mContext, "点击了搜索", Toast.LENGTH_SHORT).show();
					else
						Toast.makeText(mContext, "点击了自动横屏", Toast.LENGTH_SHORT).show();
					break;
				case 1:// 书签,检查更新
					if (isMore)
						Toast.makeText(mContext, "点击了书签", Toast.LENGTH_SHORT).show();
					else
						Toast.makeText(mContext, "点击了检查更新", Toast.LENGTH_SHORT).show();
					break;
				case 2:// 加入书签,检查网络
					if (isMore)
						Toast.makeText(mContext, "点击了加入书签", Toast.LENGTH_SHORT).show();
					else
						Toast.makeText(mContext, "点击了检查网络", Toast.LENGTH_SHORT).show();
					break;
				case 3:// 分享页面,定时刷新
					if (isMore)
						Toast.makeText(mContext, "点击了分享页面", Toast.LENGTH_SHORT).show();
					else
						Toast.makeText(mContext, "点击了定时刷新", Toast.LENGTH_SHORT).show();
					break;
				
                case 7:// 更多
					if (isMore) {
						menuGrid.setAdapter(getMenuAdapter(menu_name_array2,
								menu_image_array2));
						isMore = false;
					} else {// 首页
						menuGrid.setAdapter(getMenuAdapter(menu_name_array,
								menu_image_array));
						isMore = true;
					}
					menuGrid.invalidate();// 更新menu
					menuGrid.setSelection(7);
					break;
				default://退出, 夜间模式,刷新,设置,帮助,关于
					Toast.makeText(mContext, "点击了其它菜单项", Toast.LENGTH_SHORT).show();	
					break;
				}

			}
		});
	}

	class ClickEvent implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == btnDefaultMenu) {
				Intent it = new Intent();
				it.setClass(CustomizeMenu.this, DefaultMenu.class);
				startActivity(it);
			}
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("menu");// 必须创建一项
		return super.onCreateOptionsMenu(menu);
	}

	private SimpleAdapter getMenuAdapter(String[] menuNameArray,
			int[] imageResourceArray) {
		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < menuNameArray.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("itemImage", imageResourceArray[i]);
			map.put("itemText", menuNameArray[i]);
			data.add(map);
		}
		SimpleAdapter simperAdapter = new SimpleAdapter(this, data,
				R.layout.item_menu, new String[] { "itemImage", "itemText" },
				new int[] { R.id.item_image, R.id.item_text });
		return simperAdapter;
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (menuDialog == null) {
			menuDialog = new AlertDialog.Builder(this).setView(menuView).show();
		} else {
			menuDialog.show();
		}
		return false;// 返回为true 则显示系统menu
	}

}

主配置文件main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent" >
	
	<TextView 
	    android:layout_width="wrap_content"
		android:layout_height="wrap_content" 
		android:text="请点击 Menu键(F2)显示选项菜单"
		android:id="@+id/tvTip" />
    <Button
        android:id="@+id/btnCustomizeMenu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自定义菜单"/>
    <Button
        android:id="@+id/btnDefaultMenu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:text="系统菜单"/>
    
</LinearLayout>

菜单布局表格配置文件gridview_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <GridView
         android:id="@+id/gridview"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:numColumns="4"
         android:verticalSpacing="10dip"
         android:horizontalSpacing="10dip"
         android:stretchMode="columnWidth"
         android:gravity="center"
         />
  
</LinearLayout>

菜单项配置文件item_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/RelativeLayout_Item"
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content"
	android:paddingBottom="5dip">
	<ImageView 
	    android:id="@+id/item_image"
		android:layout_centerHorizontal="true" 
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</ImageView>
	
	<TextView 
	    android:layout_below="@id/item_image" 
	    android:id="@+id/item_text"
		android:layout_centerHorizontal="true" 
		android:layout_width="wrap_content"
		android:layout_height="wrap_content" 
		android:text="选项">
	</TextView>
	
</RelativeLayout>

开发环境:XP3+Eclipse+Android2.2+JDK6.0

测试环境:Android2.2模拟器

源代码:http://download.csdn.net/detail/xinzheng_wang/4452501

相关推荐