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

onResume()中修改菜单项报错:如何解决MenuItem空指针异常?

Fixing NullPointerException When Modifying MenuItem in onResume

Got it, let's figure out why you're hitting that NullPointerException and fix it right away. The problem here is super common—your menu object is null when you try to call getItem(1) in onResume().

Why This Happens

The menu isn't fully initialized when onResume() runs. The Android system creates and inflates the menu in the onCreateOptionsMenu() method, so you don't have a valid reference to it yet in onResume() unless you explicitly save it.

Step-by-Step Solution

  1. Add a member variable to store the menu reference
    Declare a Menu variable at the top of your Activity class:

    private Menu mMenu;
    
  2. Save the menu reference in onCreateOptionsMenu()
    Update your menu creation method to keep a reference to the inflated menu:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate your menu layout (replace with your actual menu resource ID)
        getMenuInflater().inflate(R.menu.your_menu_file, menu);
        // Save the menu reference to our member variable
        mMenu = menu;
        return true;
    }
    
  3. Modify the menu item safely in onResume()
    Now you can access the menu item, but always add null checks to avoid crashes:

    @Override
    protected void onResume() {
        super.onResume();
        // Check if the menu reference exists first
        if (mMenu != null) {
            MenuItem targetItem = mMenu.getItem(1);
            // Double-check the item itself isn't null
            if (targetItem != null) {
                targetItem.setIcon(ContextCompat.getDrawable(N_Wall_new.this, R.drawable.bil2));
            }
        }
    }
    

Extra Tips

  • Make sure the index 1 is valid for your menu (menu items are zero-indexed). If your menu has fewer than 2 items, you'll hit an IndexOutOfBoundsException next—count your items carefully!
  • For configuration changes (like screen rotation), onCreateOptionsMenu() will be called again, so your mMenu reference will automatically update without extra code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:59:42