John Mendes
John Mendes

Reputation: 789

Detecting which selected item (in a ListView multicolumn) spawned the ContextMenu (Android)

I have a ListView that will allow the user to long-press an item to get a context menu. The problem I'm having is in determining which ListItem they long-pressed. I have 3 columns, (ID, text, comment). I need retrieve the ID value when clicked.

I've tried doing this:

@Override
public boolean onContextItemSelected(MenuItem item) {
  if (item.getTitle() == "Delete") {
    View view = getWindow().getDecorView().findViewById(android.R.id.content);
    //The rowId receive the ID clicked from the listview
    rowId = ((TextView)view.findViewById(R.id.ID)).getText().toString();
    showDialog(0);
  } else return false;
  return true;
}

BUT, I always cacth the ID from the first item of listview. If I click on second item on listview, I receive the first ID on list only.

Any help please.

Thank´s in advance.

Upvotes: 0

Views: 751

Answers (2)

dymmeh
dymmeh

Reputation: 22306

Try this if you would like to extract your info from the selected View itself.

AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
View v = info.targetView;
rowId = ((TextView)v.findViewById(R.id.ID)).getText().toString();

Upvotes: 1

Rupali
Rupali

Reputation: 774

Use the below code to get the selected row index -

public boolean onContextItemSelected(MenuItem item) {
            try {
                AdapterContextMenuInfo ctxMenuInfo;
                try {
                    ctxMenuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
                } catch (ClassCastException e) { 
                    return false;
                }

                 int selectedPostion = ctxMenuInfo.position;
}

Upvotes: 1

Related Questions