首先结合如下的代码来看
package com.android.settings;import android.R.integer;import android.app.Fragment;import android.util.Log;import android.os.Bundle;import com.android.settings.ChooseLockGeneric.ChooseLockGenericFragment;import android.view.ContextMenu;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ContextMenu.ContextMenuInfo;import android.widget.Switch;/** * Stub class for showing sub-settings; we can't use the main Settings class * since for our app it is a special singleTask class. */public class SubSettings extends Settings2 { private final static int DELETE = 0; private final static int CANCEL = 1; @Override public boolean onNavigateUp() { finish(); return true; } @Override protected boolean isValidFragment(String fragmentName) { Log.d("SubSettings", "Launching fragment " + fragmentName); return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /* Vanzo:zhangshuli on: Thu, 19 Mar 2015 16:25:55 +0000 * modify for v5 calculator @Override public boolean onPrepareOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.add(0, DELETE, 0, "删除"); menu.add(0, CANCEL, 0, "取消"); return true; } */// End of Vanzo: zhangshuli @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case DELETE: break; case CANCEL: break; default: break; } return super.onOptionsItemSelected(item); } public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.add(0, DELETE, 0, "删除"); menu.add(0, CANCEL, 0, "取消"); return true; }}
1.如果我们想要实现一个optionMenu,那么我们必须找到这个activity。然后重写它的方法onCreateOptionsMenu
给onCreateOptionsMenu 添加列表有两种方式
1)直接在代码里面添加
public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.add(0, DELETE, 0, "删除"); menu.add(0, CANCEL, 0, "取消"); return true; }
menu.add()方法有四个参数
第一个:好像是给menu中的item分组,具体作用不太明白,以后遇到再研究吧
第二个:这个是item的id,我们通过menu.getitemid()得到的就是这个值
第三个:这个是我们item的排列位置,0表示默认根据添加顺序来决定位置顺序
第四个:这个就是列表中显示的内容名称
2)通过menu 中的xml添加
在menu目录下,创建一个menu.xml
代码中的引用如下
@Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu);/* Vanzo:zhangshuli on: Thu, 15 Jan 2015 15:59:26 +0000 * modify for v5 calculator getMenuInflater().inflate(R.menu.menu, menu); */// End of Vanzo: zhangshuli return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu);/* Vanzo:zhangshuli on: Thu, 15 Jan 2015 15:54:31 +0000 * modify for v5 calculator if (!sContext.getResources().getBoolean(R.bool.isTablet)) { menu.findItem(R.id.basic).setVisible(!getBasicVisibility()); menu.findItem(R.id.advanced).setVisible(!getAdvancedVisibility()); } else { menu.findItem(R.id.basic).setVisible(false); menu.findItem(R.id.advanced).setVisible(false); } */