android popupMenu

菜单项配置文件 

menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="查找" />
    <item
        android:id="@+id/add"
        android:icon="@android:drawable/ic_menu_add"
        android:title="添加" />
    <item
        android:id="@+id/edit"
        android:icon="@android:drawable/ic_menu_edit"
        android:title="编辑">
        <menu>
            <item
                android:id="@+id/copy"
                android:title="复制" />
            <item
                android:id="@+id/cut"
                android:title="剪切" />            
            <item
                android:id="@+id/paste"
                android:title="粘贴" />            
        </menu>
    </item>
    <item
        android:id="@+id/exit"
        android:title="隐藏菜单" />
</menu>

 

activity

public class PopupMenuTest extends Activity
{
    PopupMenu popup = null;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
  //此为popupMenu 按钮的响应方法
    public void onPopupButtonClick(View button)
    {
        // 创建PopupMenu对象
        popup = new PopupMenu(this, button);
        // 将R.menu.popup_menu菜单资源加载到popup菜单中
        getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
        // 为popup菜单的菜单项单击事件绑定事件监听器
        popup.setOnMenuItemClickListener(
            new PopupMenu.OnMenuItemClickListener()
        {
            @Override
            public boolean onMenuItemClick(MenuItem item)
            {
                switch (item.getItemId())
                {
                    case R.id.exit:
                        // 隐藏该对话框
                        popup.dismiss();
                        break;
                    default:
                        // 使用Toast显示用户点击的菜单项
                        Toast.makeText(PopupMenuTest.this,
                            "您单击了【" + item.getTitle() + "】菜单项"
                            , Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
        popup.show();
    }
}

 

posted on 2014-11-04 17:47  弗不是佛  阅读(238)  评论(0编辑  收藏  举报

导航