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

Navigation Drawer动态菜单项:点击时如何传值启动Intent?

处理Navigation Drawer动态菜单项的点击事件并传递数据

看起来你已经成功搞定了动态菜单项的添加,现在只需要调整onNavigationItemSelected方法的逻辑,就能实现点击动态项时启动带数据的Intent。我先帮你梳理下现有代码的问题,再给出修改方案:

现有代码的问题

  1. 语法错误:else (id == CatId) 是不正确的写法,应该用else if,但更关键的是CatId是动态生成的,没法直接用固定值判断
  2. 数据获取逻辑有问题:String tag = viewAll1.getTag().toString(); 这里的viewAll1和动态菜单项没有关联,应该从你存储的catIdList和catTitleList中获取对应的数据

修改后的完整代码

public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();
    NavigationView nv = findViewById(R.id.nav_view);
    Menu m = nv.getMenu();

    // 处理静态菜单项(比如你的nav_ebook)
    if (id == R.id.nav_ebook) {
        // 保留你原有的显示/隐藏逻辑,增加空判断避免崩溃
        int firstCatId = Integer.parseInt(catIdList.get(0));
        MenuItem dynamicItem = m.findItem(firstCatId);
        if (dynamicItem != null) {
            dynamicItem.setVisible(!dynamicItem.isVisible());
        }
    } else {
        // 处理所有动态菜单项:找到当前点击项在catIdList中的索引
        int targetIndex = -1;
        for (int i = 0; i < catIdList.size(); i++) {
            int catId = Integer.parseInt(catIdList.get(i));
            if (catId == id) {
                targetIndex = i;
                break;
            }
        }

        // 如果找到对应的动态项,启动Intent并传递数据
        if (targetIndex != -1) {
            String targetCatId = catIdList.get(targetIndex);
            String targetCatTitle = catTitleList.get(targetIndex);
            
            Intent intent = new Intent(this, AllSubCategory.class);
            intent.putExtra("ID", targetCatId);
            // 可选:如果需要传递标题,加上这行
            intent.putExtra("CATEGORY_TITLE", targetCatTitle);
            startActivity(intent);
        }
    }

    // 点击菜单项后关闭Drawer,提升用户体验
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

关键逻辑说明

  1. 区分静态与动态项:先处理固定的静态菜单项(比如nav_ebook),剩下的所有点击都归为动态项处理
  2. 匹配动态项索引:通过遍历catIdList,找到当前点击项的ID对应的索引,这样就能拿到该动态项对应的ID和标题
  3. 传递数据到目标Activity:把对应的分类ID(和标题,按需)通过Intent.putExtra传递,目标Activity可以用getIntent().getStringExtra("ID")获取数据

优化建议(可选)

为了避免每次都调用Integer.parseInt,你可以在初始化的时候把catIdList转换成整数列表:

// 在初始化catIdList之后添加
List<Integer> catIdIntList = new ArrayList<>();
for (String idStr : catIdList) {
    catIdIntList.add(Integer.parseInt(idStr));
}

之后在判断索引时可以直接用:

int targetIndex = catIdIntList.indexOf(id);

这样代码更简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:03:02