Groosha
Groosha

Reputation: 3067

Get position of selected item...?

I'm rather new to Android. Here's part of code:

protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Note selectedName = adapter.getItem(position);
adapter.removeItem(selectedName);

As you see, position means selected item position. That's good. But I'd prefer long clicks:

public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.ctxmemu_delete:
** I need to use POSITION mentioned above! **

But in this method getSelectedItemPosition returns position -9995845834585 (or smth like that) Or it gives error (can't move cursor to position - I use SQL in my app)

How can I get position from list properly? P.S. sorry for my bad English :(

UPD: I've added this to my SQL Adapter:

public int getPosition(){
return cursor.getPosition();    }

and modified:

case R.id.ctxmemu_delete:
int position = adapter.getPosition();
Note seln = adapter.getItem(position);
adapter.removeItem(seln);
return true;

for now it works...but I think it's so ugly...

Upvotes: 3

Views: 942

Answers (3)

Simon Dorociak
Simon Dorociak

Reputation: 33495

public boolean onContextItemSelected(MenuItem item) { ... }

Since you are using ContextMenu this is a little different from ItemClickListener

You can use MenuInfo for getting position in ListView

AdapterView.AdapterContextMenuInfo info = 
                         (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

Where it has int property info.position that returns position in the adapter for which the context menu was displayed.

Note: You can also have look at OnItemLongClickListener with works similar.

Upvotes: 1

Swayam
Swayam

Reputation: 16354

Why don't you use a onListItemLongClick listener instead of going for the context menu ?

protected void onListItemLongClick(ListView l, View v, int position, long id) {
super.onListItemLongClick(l, v, position, id);
Note selectedName = adapter.getItem(position);
adapter.removeItem(selectedName);
}

Upvotes: 1

Bill Mote
Bill Mote

Reputation: 12823

You just need to use onListItemLongClick() instead of onListItemClick().

Upvotes: 1

Related Questions