onResume()中修改菜单项报错:如何解决MenuItem空指针异常?
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
Add a member variable to store the menu reference
Declare aMenuvariable at the top of your Activity class:private Menu mMenu;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; }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
1is valid for your menu (menu items are zero-indexed). If your menu has fewer than 2 items, you'll hit anIndexOutOfBoundsExceptionnext—count your items carefully! - For configuration changes (like screen rotation),
onCreateOptionsMenu()will be called again, so yourmMenureference will automatically update without extra code.
内容的提问来源于stack exchange,提问作者Isee You

