[Android]菜单简介和实现

在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值