0

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).

pnuts
  • 58,317
  • 11
  • 87
  • 139
Otto
  • 19
  • 8

2 Answers2

2

In your menu.xml file you define an id for the item e.g. @+id/menu_item

<item
        android:id="@+id/menu_item"
        android:icon="@drawable/item"
        android:title="Item"
        android:visible="true"
        app:showAsAction="ifRoom" />

Then in your switch, you add R.id.menu_item:

//...
switch(item.getItemId()) {
            case R.id.menu_item:
                doAction();
                break;
//...
Maciej Beimcik
  • 3,218
  • 1
  • 24
  • 26
0

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
}
  • It seems too be right exept that i cannot resolve the symbol mi in my mainactivity – Otto Aug 02 '18 at 20:53
  • Declare it on top just before onCreate(); –  Aug 02 '18 at 20:55
  • How would you do that? – Otto Aug 02 '18 at 21:11
  • see my edited answer. The variable mi needs to be global in the activity. –  Aug 02 '18 at 21:13
  • My "mi = menu.add(0,0,0, "Slet denne regning");" is in another class, than MainActivity :P – Otto Aug 02 '18 at 21:19
  • What is this a popup menu or the activity's main menu? –  Aug 02 '18 at 21:23
  • Well it is a menu that popups from a recyclerView item. so i have created the menu itself in my recyclerView adapter, and then afterwards called the menu in my mainactivity to make it apear, wich also is where i give it actions. – Otto Aug 02 '18 at 21:25
  • Yeah but that might still be the problem, thank you for the help :) but i'll have to look at it toomorrow :) – Otto Aug 02 '18 at 21:42