Android Menu

1.ContextMenu

上下文菜单,就是长按某个控件后弹出菜单

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);
    }

2.PopupMenu

// Show Popup Menu
void showPopupMenu(){

    // 为View指定 PopupMenu
    PopupMenu pm=new PopupMenu(MenuActivity.this,btnPopupMenu);
    // 指定 Menu 文件
    pm.getMenuInflater().inflate(R.menu.menu_test,pm.getMenu());
    //Item 点击事件
    pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()){
                case R.id.menu_item1:
                    toast("Menu1");
                    break;
                case R.id.menu_item2:
                    toast("Menu2");
                    break;
            }
            return true;
        }
    });
    pm.show(); //显示
}

Android Menu

上一篇:小心 HttpClient 中 FormUrlEncodeContent 的 bug


下一篇:Android 博客导航