onOptionsItemSelected not called
17,252
Solution 1
Inside your onCreateOptionsMenu
, return true instead of calling super. That should do it
Solution 2
In the onCreate(), call setSupportActionbar(), like so
toolbar = (Toolbar)findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
Solution 3
Just do the change as below :
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
Related videos on Youtube
Author by
bear
Updated on June 04, 2022Comments
-
bear about 2 years
I have a list of menu items in my actionbar. Each item click should trigger a different method. But onOptionsItemSelected is never called.
This is how the actionbar is defined in MainActivity:
public class MainActivity extends AppCompatActivity { ... @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings_1) { //do something return true; } else if (id == R.id.action_settings_2) { //do something return true; } else if (id == R.id.action_settings_1) { //do something return true; } return super.onOptionsItemSelected(item); } ... }
This is the actionbar menu layout menu_main:
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.example.MainActivity"> <item android:id="@+id/action_settings_1" android:orderInCategory="1" android:title="Item 1" app:showAsAction="never" /> <item android:id="@+id/action_settings_2" android:orderInCategory="2" android:title="Item 2" app:showAsAction="never" /> <item android:id="@+id/action_settings_3" android:orderInCategory="3" android:title="Item 3" app:showAsAction="never" /> </menu>
How can I set up the actionbar so that onOptionsItemSelected is called when an actionbar item is clicked?
-
Amit Thaper over 4 yearsThere is no return type of boolean in this override method
-
Rui Cardoso over 4 yearsThis in on the Activity. The return type is void on the Fragment
-
truthadjustr about 4 yearsHow about for
ListActivity
i tried it does not work -
truthadjustr about 4 yearsCannot find
R.menu
normenu_main
where is it