Menu的总结

系统菜单

首先要在R文件下创建名字menu的文件夹
在menu文件夹中创建menu布局
然后再Activity中重写onCreateOptionsMenu()方法
onOptionsItemSelected()方法是menu的点击事件

//系统菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //获取菜单解析器
        MenuInflater menuInflater = getMenuInflater();
        //解析menu布局
        menuInflater.inflate(R.menu.menu_option,menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {//参数为当前点击的菜单选项
        Toast.makeText(this, "menu的下标:"+item.getItemId()+"-----标题为:"+item.getTitle(), Toast.LENGTH_SHORT).show();
        switch (item.getItemId()){
            case R.id.item1:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

上下文菜单

哪个控件需要添加上下文,就在初始化控件完后,把空间放到registerForContextMenu()里面
然后再重写onCreateContextMenu()方法

 //上下文菜单
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        getMenuInflater().inflate(R.menu.menu_option,menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        content1.setText(item.getTitle());
        return super.onContextItemSelected(item);
    }

弹出框菜单

需要自己自定义布局并解析
我这边是封装了一个方法

private void showPopupWindow(){
        //需要布局解析器解析自定义布局
        View view = LayoutInflater.from(this).inflate(R.layout.pupupwindow_layout_up,null);

        PopupWindow popupWindow = new PopupWindow(this);
        //将解析好的布局放到弹出菜单中
        popupWindow.setContentView(view);
        //设置弹出框的高
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置弹出框的宽
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        View parent = LayoutInflater.from(this).inflate(R.layout.activity_popup_window,null);
        //设置弹出的位置
        popupWindow.showAsDropDown(parent,0,0);
        popupWindow.showAtLocation(parent, Gravity.CENTER,0,0);
    } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值