You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中选中上下文菜单项时Toast消息不显示的问题

问题解决:上下文菜单选中后Toast不显示

核心原因

你的onContextItemSelected方法仅对菜单项ID做了判断,但完全没有添加Toast的显示逻辑,所以选中菜单项时不会触发任何提示。

修复代码

修改MainActivity.java中的onContextItemSelected方法,加入Toast展示代码:

@Override
public boolean onContextItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.context_item_1) {
        Toast.makeText(this, "已选中Context Item 1", Toast.LENGTH_SHORT).show();
        return true;
    }

    if (id == R.id.context_item_2) {
        Toast.makeText(this, "已选中Context Item 2", Toast.LENGTH_SHORT).show();
        return true;
    } else {
        return super.onContextItemSelected(item);
    }
}

额外优化提示

  • 使用this作为Toast的上下文比getApplicationContext()更合适,能更好贴合当前Activity的生命周期
  • 你当前通过ActionBar返回按钮触发上下文菜单的写法可以简化,建议在onCreate中提前注册根视图的上下文菜单,避免每次点击都重复注册/注销:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle("Home Activity");

    Toast.makeText(this,"Hello Javatpoint",Toast.LENGTH_SHORT).show();
    // 提前注册上下文菜单,无需每次点击重复操作
    registerForContextMenu(findViewById(android.R.id.content));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        openContextMenu(findViewById(android.R.id.content));
        return true;
    }

    return super.onOptionsItemSelected(item);
}

内容的提问来源于stack exchange,提问作者hee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 22:14:53