Toolbar选项按钮在新Activity中无法点击问题求助
Hey there, let’s figure out why your Toolbar buttons stopped responding when you moved the setup to another Activity. Since everything worked flawlessly in activity_one, the issue is almost certainly related to how the new Activity is configured—not the Toolbar code itself. Here are the most common fixes to check:
Ensure you’re setting the Toolbar as the Activity’s ActionBar
This is the most frequent culprit. In your new Activity’sonCreate()method, did you callsetSupportActionBar()on your Toolbar? Without this, the system won’t recognize your custom Toolbar as the official ActionBar, so menu click events won’t be routed properly. Example code:// Inside your new Activity's onCreate() val toolbar = findViewById<Toolbar>(R.id.your_toolbar_id) setSupportActionBar(toolbar)Double-check that your new Activity uses a
NoActionBartheme too—if it’s using a theme with a default ActionBar, your custom Toolbar might be rendered but ignored for menu interactions.Confirm menu inflation and click handling are implemented
Make sure you’ve overridden bothonCreateOptionsMenuandonOptionsItemSelectedin the new Activity. It’s easy to forget to copy these methods over when migrating code. Here’s what they should look like:override fun onCreateOptionsMenu(menu: Menu?): Boolean { // Inflate the same menu resource you used in activity_one menuInflater.inflate(R.menu.your_toolbar_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.your_menu_item_1 -> { // Execute your button action here true } R.id.your_menu_item_2 -> { // Handle another button true } else -> super.onOptionsItemSelected(item) } }Also verify that the menu item IDs in this method match exactly what’s in your menu XML file—typos here will make clicks seem unresponsive.
Check for conflicting layout attributes
Inspect the Toolbar’s layout XML in the new Activity. Did you accidentally setandroid:clickable="false"orandroid:focusable="false"? Even if the original layout didn’t have these, they might have been added during migration. Also, check if the Toolbar’s parent container (like aCoordinatorLayoutorDrawerLayout) is intercepting touch events—try addingandroid:clickable="true"to the Toolbar to force it to receive clicks first.Verify you’re using the correct menu resource
It’s possible you accidentally referenced a different menu XML file in the new Activity. Compare the menu resource ID used inonCreateOptionsMenuwith the one fromactivity_oneto ensure they’re identical. A mismatched menu file could show the right buttons but lack the correct click bindings.
Since your Toolbar works perfectly in the first Activity, the fix is likely a small missed setup step. Go through these checks one by one, and you’ll probably spot the issue quickly!
内容的提问来源于stack exchange,提问作者Boris Ruzanov

