Android Menu
Android - Menu
1.ContextMenu
上下文菜单,就是长按某个view后弹出菜单。关联的是View。
效果图:
1.1选项菜单Menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="none">
<item android:id="@+id/item_context_item1" android:title="Item1"/>
<item android:id="@+id/item_context_item2" android:title="Item2"/>
<item android:id="@+id/item_context_item3" android:title="Item3"/>
</group>
</menu>
1.2 为View注册上下文菜单
registerForContextMenu(view);
1.3创建Menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflator=new MenuInflater(this);
inflator.inflate(R.menu.menu_context,menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
1.4 Item 点击事件
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.item_context_item1:
toast("Item1");
break;
....
}
return super.onContextItemSelected(item);
}
1.5 ListView 注册 ContextMenu
registerForContextMenu(lv)
通过 AdapterContextMenuInfo
来获取是点击Item
的 Position
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Toast.makeText(this, "menuInfo.position:" + menuInfo.position, Toast.LENGTH_SHORT).show();
return super.onContextItemSelected(item);
}
2.PopupMenu
// Show Popup Menu
void showPopupMenu(Context mContext,View view){
// 为View指定 PopupMenu
PopupMenu pm=new PopupMenu(mContext,view);
// 指定 Menu 文件
pm.getMenuInflater().inflate(R.menu.menu_test,pm.getMenu());
//Item 点击事件
pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
toast(item.getTitle());
return true;
}
});
pm.show(); //显示
}
文章部分内容摘自网络和图书,如有侵权,请联系我。