在Android中,通常有3种菜单:
1、操作菜单
这种菜单按Menu键时会弹出来,比如:
2、上下文菜单
这种菜单在屏幕中长按触发菜单项,当然,没有未设置上下文菜单,则无响应,比如:
3、子菜单
顾名思义,也就是菜单的菜单,在Android中,只支持两层菜单,也就是不允许子菜单再有子菜单,比如这里的操作菜单我实现了两个子菜单,单击操作,则:
下面一一实现这几种菜单
操作菜单:
主要是这两个接口:
public boolean onCreateOptionsMenu(Menu menu);
public boolean onOptionsItemSelected(MenuItem item);
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
menu.add(0,1,0,"Red");
menu.add(0,2,0,"Yellow");
menu.add(0,3,0,"Clean");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
Log.v(TAG, "--onOptionsItemSelected--");
TextView txt = (TextView)findViewById(R.id.textView1);
if(1 == item.getItemId()){
txt.setBackgroundColor(Color.RED);
}
else if(2 == item.getItemId()){
txt.setBackgroundColor(Color.YELLOW);
}
else if(3 == item.getItemId()){
txt.setText("");
}
return super.onOptionsItemSelected(item);
}
这里使用的menu.add原型为:
public abstract MenuItem add (int groupId, int itemId, int order, CharSequence title)
上下文菜单/子菜单
主要是这两个接口:
public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo);
public boolean onContextItemSelected (MenuItem item);
示例代码:
public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
if(v == act){
menu.setHeaderTitle("Action ContextMenu");
menu.add(0, 1, 1, "Abotu");
}
else if(v == pos){
menu.setHeaderTitle("Postion ContextMenu");
menu.add(0, 2, 2, "Abotu Postion");
SubMenu sm = menu.addSubMenu("操作");
sm.add(0, 3, 3, "字体增大");
sm.add(0, 4, 4, "颜色改变");
}
}
public boolean onContextItemSelected (MenuItem item){
if(1 == item.getItemId() || 2 == item.getItemId()){
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
}
else if(3 == item.getItemId()){
pos.setTextSize(18);
}
else if(4 == item.getItemId()){
pos.setTextColor(Color.RED);
}
return super.onContextItemSelected(item);
}
需要注意的是,这里也建立了两个子菜单,使用很简单,具体可以参考下SubMenu