Android 菜单(OptionMenu)
转载自 http://www.cnblogs.com/salam/archive/2011/04/04/2005329.html
菜单是用户界面中最常见的元素之一,使用非常频繁,在Android中,菜单被分为如下三种,选项菜单(OptionsMenu)、上下文菜单(ContextMenu)和子菜单(SubMenu),今天这讲是OptionsMenu
一、概述
public boolean onCreateOptionsMenu(Menu menu):使用此方法调用OptionsMenu 。
public boolean onOptionsItemSelected(MenuItem item):选中菜单项后发生的动作。
public void onOptionsMenuClosed(Menu menu):菜单关闭后发生的动作。
public boolean onPrepareOptionsMenu(Menu menu):选项菜单显示之前onPrepareOptionsMenu方法会被调用,你可以用此方法来根据打当时的情况调整菜单。
public boolean onMenuOpened(int featureId, Menu menu):单打开后发生的动作。
二、默认样式
默认样式是在屏幕底部弹出一个菜单,这个菜单我们就叫他选项菜单OptionsMenu,一般情况下,选项菜单最多显示2排每排3个菜单项,这些菜单项有文字有图标,也被称作Icon Menus,如果多于6项,从第六项开始会被隐藏,在第六项会出现一个More里,点击More才出现第六项以及以后的菜单项,这些菜单项也被称作Expanded Menus。
效果图如下:
图一(系统默认样式)
图二(自定义菜单样式)
(实际上是使用了自定义布局对话框 来实现图二这菜单风格的)
图一(系统默认样式):对应配置和代码
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键显示选项菜单" /> </LinearLayout>
Activity代码:
//定义选项菜单
private String[] allOptionsMenuTexts = {"删除","保存","帮助","添加","详细","发送","电话","照相"};
private int[] allOptionsMenuOrders = {5,2,6,1,4,3,7,8};
private int[] allOptionsMenuIds = {Menu.FIRST+1,Menu.FIRST+2,Menu.FIRST+3,Menu.FIRST+4,Menu.FIRST+5,Menu.FIRST+6,Menu.FIRST+7,Menu.FIRST+8};
private int[] allOptionsMenuIcons = {
android.R.drawable.ic_menu_delete,
android.R.drawable.ic_menu_edit,
android.R.drawable.ic_menu_help,
android.R.drawable.ic_menu_add,
android.R.drawable.ic_menu_info_details,
android.R.drawable.ic_menu_send,
android.R.drawable.ic_menu_call,
android.R.drawable.ic_menu_camera
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/*
* add()方法的四个参数,依次是:
* 1、组别,如果不分组的话就写Menu.NONE,
* 2、Id,这个很重要,Android根据这个Id来确定不同的菜单
* 3、顺序,菜单显示排序编号,编号小的排在前面
* 4、文本,菜单的显示文本
*/
for(int i=0;i<allOptionsMenuTexts.length;i++){
menu.add(Menu.NONE, allOptionsMenuIds[i],allOptionsMenuOrders[i],allOptionsMenuTexts[i])
.setIcon(allOptionsMenuIcons[i]);
}
/*
* 这里必须返回true.
* 如果返回false,则点Menu按键将不起任何作用.
*/
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
Toast.makeText(this, allOptionsMenuTexts[itemId-2]+"菜单被点击了", Toast.LENGTH_LONG).show();
return true;
}
@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();
/*
* 这里必须返回true.
* 如果返回false,则后面的onCreateOptionsMenu方法将不会被执行,定义的选项菜单也就不会显示出来。
*/
return true;
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
Toast.makeText(this, "选项菜单打开了"+featureId, Toast.LENGTH_LONG).show();
/*
* 这里必须返回true.
* 如果返回false,
* 则后面会继续执行onPrepareOptionsMenu方法,
* 但之后的onCreateOptionsMenu方法不会执行,
* 也就不会显示选项菜单了。
*/
return true;
}
图二( 自定义菜单样式 ):对应配置和代码
(备注:图二例子的完整代码位于后面的附件 ANDROID2.2_Menu1.rar 中 )
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键显示选项菜单" /> </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" /> <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" /> </RelativeLayout>
Activity代码
package com.zhouzijing.android;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Menu1Activity extends Activity {
//menu菜单翻页控制:默认为true:表示先显示首页菜单,可以翻页
private boolean isMore = true;
//menu菜单Dialog
AlertDialog menuDialog;
private final int ITEM_MORE = 11;// 菜单[更多、返回]
/** 菜单图片 **/
int[] menu_image_array = { R.drawable.menu_search,
R.drawable.menu_filemanager, R.drawable.menu_downmanager,
R.drawable.menu_fullscreen, R.drawable.menu_inputurl,
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_penselectmodel, R.drawable.menu_page_attr,
R.drawable.menu_novel_mode, R.drawable.menu_page_updown,
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);
//创建menu对话框
createMenuDialog();
}
private void createMenuDialog() {
final Context context = this;
//初始化自定义布局参数
LayoutInflater layoutInflater = getLayoutInflater();
View menuView = layoutInflater.inflate(R.layout.gridview_menu, null);
// 创建1个自定义布局的AlertDialog
menuDialog = new AlertDialog.Builder(context).setView(menuView).setOnKeyListener(new OnKeyListener(){
@Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
//如果点击手机的[menu]键则关闭菜单对话框.
if(keyCode==KeyEvent.KEYCODE_MENU){
menuDialog.dismiss();
}
return false;
}
}).create();
//获取GridView组件
final GridView menuGrid = (GridView) menuView.findViewById(R.id.gridview);
//预先定义的2组菜单
final SimpleAdapter[] menuAdapters = {
createMenuAdapter(menu_name_array, menu_image_array),
createMenuAdapter(menu_name_array2, menu_image_array2)
};
//将GridView组件通过适配器配置事先设计好的菜单
menuGrid.setAdapter(menuAdapters[0]);
/** 监听menu选项 **/
menuGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int selectedMenuId = arg2;//当前点击的菜单按钮的编号
String[] menuNames = null;
String selectedMenuName = null;
menuNames = (isMore)?menu_name_array:menu_name_array2;
selectedMenuName = menuNames[selectedMenuId];
Toast.makeText(context, "菜单["+selectedMenuName+"]点击了.", Toast.LENGTH_SHORT).show();
//点击菜单按钮[更多/返回]执行的操作
int menuMore = ITEM_MORE;
if(selectedMenuId==menuMore){
menuGrid.setAdapter(menuAdapters[(isMore)?1:0]);
isMore=!isMore;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Toast.makeText(this, "do:onCreateOptionsMenu", Toast.LENGTH_SHORT).show();
menu.add("menu");// 必须创建一项
return super.onCreateOptionsMenu(menu);
}
private SimpleAdapter createMenuAdapter(String[] menuNames,int[] menuImages){
List<Map<String,?>> data = new ArrayList<Map<String,?>>();
String[] adapterFroms = {"itemText","itemImage"};
int[] adapterTos = {R.id.item_text,R.id.item_image};
for(int i=0;i<menuNames.length;i++){
Map<String,Object> map = new HashMap<String,Object>();
map.put(adapterFroms[0], menuNames[i]);
map.put(adapterFroms[1], menuImages[i]);
data.add(map);
}
SimpleAdapter menuSimpleAdapter = new SimpleAdapter(this,data,
R.layout.item_menu,adapterFroms,adapterTos);
return menuSimpleAdapter;
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
Toast.makeText(this, "do:onMenuOpened", Toast.LENGTH_SHORT).show();
//显示menu对话框
menuDialog.show();
return false;// 返回为true 则显示系统menu
}
}