How do you make it when the user touches the menu symbol and the message appears in Toast?

Asked

Viewed 69 times

1

I have this method but it doesn’t work what 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;
}

}

2 answers

1

If you are inflating the menu layout, you can add the item there in the same xml, need not 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, take it by ID.

example:

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

1


Try to change onMenuItemSelected for onOptionsItemSelected!

Follow an example:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.