Prashant Sharma Prashant Sharma - 5 months ago 77
Android Question

onItemLongClickListener is working weird

My code is below
my problem is when activity is first open long click on listview is not working.And then again i hold the item in listview it will work.why this happening anyone has any idea.
Thanks in Advance

editListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

editListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
editListView.setMultiChoiceModeListener(new ListView.MultiChoiceModeListener() {
@Override
public void onItemCheckedStateChanged(ActionMode actionMode, int position, long l, boolean b) {
actionMode.setTitle(editListView.getCheckedItemCount() + " Selected");

// Toggle the state of item after every click on it
mAdapterEdit.toggleSelection(position);
}

@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.menu_group_edit, menu);
return true;
}

@Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}

@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
if (menuItem.getItemId() == R.id.delete_action) {

SparseBooleanArray selected = mAdapterEdit.getSelectedIds();
short size = (short) selected.size();
for (byte I = 0; I < size; I++) {
if (selected.valueAt(I)) {
GroupContactDAO selectedItem = mAdapterEdit
.getItem(selected.keyAt(I));
mAdapterEdit.remove(selectedItem);
}
}
actionMode.finish();
return true;
}
return false;
}

@Override
public void onDestroyActionMode(ActionMode actionMode) {

}
});

return false;
}
});

Answer

The problem is you're calling setChoiceMode() and setMultiChoiceModeListener() inside your OnItemLongClickListener, which means these methods will not get called until you perform a long click on a list item.

Put editListView.setChoiceMode() and editListView.setMultiChoiceModeListener() outside of your OnItemLongClickListener:

editListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
editListView.setMultiChoiceModeListener(new ListView.MultiChoiceModeListener() {
    // ...
}

editListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    // ...
}