Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onOptionsItemSelected not called

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?

like image 769
bear Avatar asked Mar 09 '17 21:03

bear


Video Answer


2 Answers

In the onCreate(), call setSupportActionbar(), like so

toolbar = (Toolbar)findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
like image 123
wat er Avatar answered Sep 29 '22 09:09

wat er


Inside your onCreateOptionsMenu, return true instead of calling super. That should do it

like image 28
Rui Cardoso Avatar answered Sep 29 '22 09:09

Rui Cardoso