javaandroidandroid-studiomenu-items

Referencing a menu itemId in android studio


I was wondering how i reference the menu Item i have created, in my switch? Thank you in advance.

MY menu Item:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, 
ContextMenu.ContextMenuInfo menuInfo) {

        menu.setHeaderTitle("Vælg en handling");

        //I just want one of the menu items under referenced.
        menu.add(0,0,0, "Slet denne regning");
        menu.add(0,1,0, "Omdøb denne regning");

    }

And my Switch Case:

@Override
public boolean onContextItemSelected(MenuItem item) {
    adapter.getSelectedItem(item);

    switch (item.getItemId()){
        case //This is where i want one of my menu items referenced :
            finish();
    }

    return super.onContextItemSelected(item);
}

It should also be noted that my switch is in my mainActivity, and my Menu item is in another class(A Recycler adapter).


Solution

  • Declare in your activity:

    public class MainActivity extends AppCompatActivity {
        MenuItem mi;
    

    The add method returns the menuitem:

    mi = menu.add(0,0,0, "Slet denne regning");

    and in onContextItemSelected:

    if (item == mi) {
      //your code here
    }