ListView.getSelectedItemPosition () return index-1

I have my own custom listview, and at the end of each row I have an ImageView to remove this row from the list, but when I click on this image, I get "Arryindesoutofboundexception: length = 681 indez = -1"

help me

private OnClickListener imageviewClickListener = new OnClickListener() { @Override public void onClick(View v) { int index; index=listView.getSelectedItemPosition();//itemsListView is the listview dataAdapter.remove(topicsList.get(index)); topicsList.clear(); dataAdapter.notifyDataSetChanged(); } }; 
+4
source share
2 answers

Your item is not selected because the image captures a touch event, so the selected position is -1. To do this, you need to tell OnClickListener to which element it belongs:

 private static class MyClickListener implements OnClickListener { private final int mIndex; private MyClickListener (int index) { mIndex = index; } @Override public void onClick(View v) { dataAdapter.remove(topicsList.get(mIndex)); topicsList.clear(); dataAdapter.notifyDataSetChanged(); } } 
+4
source

You are trying to get the position of the selected item from the ListView , even if there was no selected item. From the getSelectedItemPosition() documents, you can see that if no item is selected, it returns INVALID_POSITION , which is -1 .

+1
source

All Articles