Search code examples
androidoptionmenu

Option menu option not directing to another activity


I want to navigate to another Activity when click on the option menu item 'settings' from the menu bar. Nothing actual happens.I have checked similar issues posted here, but i can understand why this is not working for option menu. see the code below:

Can't go to a new activity from selected option from option menu

<item
    android:id="@+id/mySettings"

    android:title="@string/action_settings" />

<item
    android:id="@+id/logout"

    android:title="log out" />

code:

public class Dashboard extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.app_bar_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }


    public void openConfigure(){
        Intent intent = new Intent(this,Configure.class);
        this.startActivity(intent);
    }
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.mySettings:
                openConfigure();

                break;

            default:
                return super.onOptionsItemSelected(item);

        }


        return true;
    }

Solution

  • Use onOptionsItemSelected instead of onContextItemSelected cause you are using OptionMenu not ContextMenu.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.mySettings:
                openConfigure();
                break;
        }
        return super.onOptionsItemSelected(item);
    }