Menu菜单 程序定义
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.main, menu);
MenuItem it= menu.add(0, 1, 1, "菜单1");
it.setIcon(R.drawable.s5);
menu.add(0, 2, 2, "哈哈");
menu.add(0, 3, 3, "退出系统");
Menu it2=menu.addSubMenu(0, 4, 4, "2级菜单");
it2.add(1, 11, 1, "有1");
it2.add(1, 12, 2, "有2");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId())//得到被点击的item的itemId
{
case 1: //对应的ID就是在add方法中所设定的Id
Toast.makeText(getBaseContext(), "菜单"+item.getItemId(), Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getBaseContext(), "哈哈", Toast.LENGTH_SHORT).show();
break;
case 3:
finish();
break;
}
return true;
}
}
---------------------------------------------------------------
Menu菜单 xml定义
getMenuInflater().inflate(R.menu.main, menu);
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings" //id
android:orderInCategory="1" //显示顺序
android:showAsAction="never" //显示方式 显示在ifRoom标题栏上 never 不显示
android:icon="@drawable/s5" //图片
android:title="@string/action_settings"/> //文字提示
<item android:id="@+id/item1"
android:title="菜单"
android:orderInCategory="4" >
<menu> //2级菜单
<item android:id="@+id/item2" android:title="caidan"/>
<item android:id="@+id/item3" android:title="2个哦"/>
</menu>
</item>
<item android:id="@+id/item4" android:title="我是1级"></item>
</menu>
-------------------------------------------------------------------------
VIEW 绑定长按弹出菜单
listView1=(ListView)this.findViewById(R.id.listView1);
ArrayAdapter ad = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,ls);
listView1.setAdapter(ad);
registerForContextMenu(listView1); //注册长按弹出控件
@Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuinfo){
super.onCreateContextMenu(menu, v, menuinfo);
MenuInflater itml=getMenuInflater();
itml.inflate(R.menu.alert_menu,menu); //布局.
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), item.getItemId()+"ID", 3).show();
return super.onContextItemSelected(item);
}
R.menu.alert_menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/item1" android:title="删除"></item>
<item android:id="@+id/item2" android:title="修改"></item>
<item android:id="@+id/item3" android:title="放弃"></item>
</menu>
------------------------------------------------------------
没整明白。。
PopupMenu pm =new android.widget.PopupMenu(MainActivity.this, v);
pm.setOnMenuItemClickListener(itemCK);
pm.inflate(R.menu.alert_menu);
pm.show();
final OnMenuItemClickListener itemCK= new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this, item.getItemId(), 3).show();
return true;
}
};