android: listview long click & context popup causing stackoverflowerror (possibly due to actionbarsherlock?)

StackOverflow https://stackoverflow.com/questions/16170264

Frage

I cannot for the life of me figure out why this is happening. I've looked through the ABS sample code (which works fine for non-listviews), I've searched online and followed instructions correctly, but still I have some strange bug.

During my onCreate() I call this code:

lv.setOnItemLongClickListener(new OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        registerForContextMenu(view);
        openContextMenu(view);
        return true;
    }
});

When long clicking the item, for some reason it keeps going from:

  • (line 6) openContextMenu()
  • View.showContextMenu()
  • AbsListView.showContextMenuForChild()
  • back to (line 6) openContextMenu()

I do have a click listener set, but it shouldn't be affecting anything as it opens a new activity if clicked.

For completeness, here's the context menu creation.

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    if (v.getId() == R.id.lvFines) {
        menu.add("One");
        menu.add("Two");
        menu.add("Three");
        menu.add("Four");
    }
}

Am I using the wrong "support" function from ActionBarSherlock?

War es hilfreich?

Lösung

Well, I feel silly now that I've fixed it so soon after posting the question.

The problem was the onItemLongClick() method, do not use it for context menu.

Instead, register the LISTVIEW for the context menu.

Here's the source.

for onCreate():

registerForContextMenu(lv);

And to access the selected item during long click:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    if (v.getId() == R.id.lv) {
        ListView lv = (ListView) v;
        AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
        YourObject obj = (YourObject) lv.getItemAtPosition(acmi.position);

        menu.add("One");
        menu.add("Two");
        menu.add("Three");
        menu.add(obj.name);
    }
}

That's all folks!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top