弹出菜单PopupMenu

钱志强
2023-12-01
//popup_btn:演示
final Button popupBtn = findViewById(R.id.popup_btn);
findViewById(R.id.popup_btn).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        //①实例化弹出菜单PopupMenu对象(参数二:被锚定的view)
        PopupMenu menu = new PopupMenu(MainActivity2.this,popupBtn);
        //②加载菜单资源:利用Menulnflater将Menu资源加载到PopupMenu.getMenu()所返回的Menu对象中
        menu.getMenuInflater().inflate(R.menu.popup,menu.getMenu());
        //③为PopupMenu设置点击监听器
        menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.copy:
                        Toast.makeText(MainActivity2.this, "复制", Toast.LENGTH_SHORT).show();
                }

                switch (menuItem.getItemId()){
                    case R.id.paste:
                        Toast.makeText(MainActivity2.this, "粘贴", Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });
        //④千万不要忘记这一步
        menu.show();
    }
});

 类似资料: