How do you do when the user touches the menu symbol appears in the Toast?

1

I have this method but it does not work what do I do? :

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.menu, menu);
    MenuItem menuTeste = menu.add(0, 0, 0, "Item teste");
    menuTeste.setIcon(R.drawable.adcsimbolo);
    menuTeste.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    return true;
}




  public boolean onMenuItemSelected (MenuItem menuItem){
    //super.onMenuItemSelected(add,menuItem);
    switch (menuItem.getItemId()){
        case 0 :
            Toast.makeText(CadastroActivity.this, "Tocado", Toast.LENGTH_SHORT).show();
            break;
    }
    return true;
}

}

    
asked by anonymous 09.12.2016 / 17:18

2 answers

1

Try switching onMenuItemSelected to onOptionsItemSelected !

Here's an example:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case 0 :
                Toast.makeText(this, "Tocado", Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }
    
09.12.2016 / 17:37
1

If you are inflating the menu layout, you can add the item there in the same xml, it does not need to be programmatically.

example:

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/item_teste"
        android:icon="@drawable/adcsimbolo"
        android:title="Item teste"
        app:showAsAction="always" />

</menu>

And to get the item that was clicked and show Toast, get the ID.

example:

switch (menuItem.getItemId()){
   case R.id.item_teste:
       Toast.makeText(CadastroActivity.this, "Tocado", Toast.LENGTH_SHORT).show();
   break;
}
    
09.12.2016 / 17:25