I have made a context menu but I cant get the itemListener to work because I cant use switch-case for the selected title(since it works only for Integer,Not string).
I want to do something upon clicking the item. Although I can do it with (IF statement).
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
View view=findViewById(R.id.myView);
registerForContextMenu(view);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "Item 1");
menu.add(0, v.getId(), 0, "Item 2");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case 0: Toast.makeText(this, "Item selected 1", Toast.LENGTH_SHORT).show();
break;
case 1: Toast.makeText(this, "Item selected 2", Toast.LENGTH_SHORT).show();
break;
default:
}
return true;
}
You’re setting both the IDs for your options to the same thing, so this won’t work. The second argument in the
add()method is supposed to be a unique ID to allow you to determine the option clicked later on. Try something like: