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?
Inside your onCreateOptionsMenu
, return true instead of calling super. That should do it