一,静态XML加载MENU
1,创建menu文件夹下的menu.xml文件
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/menu_setting"
android:title="Setting_222"
/>
<item
android:id="@+id/menu_setting2"
android:title="information"
/>
</menu>
2,复写onCreateOptionsMenu方法:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/**
* 静态加载Menu菜单
*/
getMenuInflater().inflate(R.menu.menu,menu);
return true;
//return super.onCreateOptionsMenu(menu);
}
3,menu菜单监听事件
复写onOptionsItemSelected
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_setting:
Log.i(TAG, "onOptionsItemSelected: -->"+"menu_setting");
Toast.makeText(this,"点击了菜单一",Toast.LENGTH_LONG);
break;
case R.id.menu_setting2:
Log.i(TAG, "onOptionsItemSelected: hhahahaah");
Toast.makeText(this,"点击了菜单2",Toast.LENGTH_LONG);
break;
}
return super.onOptionsItemSelected(item);
}
二、动态创建菜单
1,重新onCreateOptionsMenu
MenuItem menu1 = menu.add(1,100,1,"menu1");
menu.add(1,101,1,"menu2");
menu.add(1,102,1,"menu3");
return true;
2,监听Menu菜单
同上。只是id为100,101和102
三 ContextMenu
主要用于listview以及gridview上长时间按ITEM时弹出的菜单
1,创建menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/edit_menu"
android:title="Edit"
/>
<item android:id="@+id/delete_menu"
android:title="Delete"
/>
</menu>
2,创建listview,并调用registerForContextMenu();
list = (ListView)findViewById(R.id.list);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,str);
list.setAdapter(arrayAdapter);
registerForContextMenu(list);
3,重写onCreateContextMenu,onContextItemSelected
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu,menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.edit_menu:
Log.i(TAG, "onContextItemSelected: --->menu edit");
return true;
case R.id.delete_menu:
Log.i(TAG, "onContextItemSelected: --->delete");
return true;
default:
return super.onContextItemSelected(item);
}
}