I would like to know how to remove an item (which the user can select) from the ListView in the user interface. ListView contains only TextViews that show the IP address. Now, when I click the (Delete) button, I want to remove the selected item from the ListView.
Now I track the selected items using the ArrayList array, which stores the item indices. I set the SelectionMode ListView parameter to multipleChoice, so these indices must be accurate. I donβt know how to do this, but my way looks like this:
mEndPointList.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){ boolean found = false; int index = 0; while(!found && index >= 0 && index < mSelectedItems.size()){ if(mSelectedItems.get(index).intValue() == arg2){ found = true; } index++; } if(!found){ mSelectedItems.add(new Integer(arg2)); } } });
Now, when I finish the selection of elements, I click the "Delete" button, which should delete the elements in the saved indexes. The code from the button is as follows:
public class RemoveItemButtonHandler implements OnClickListener{ @Override public void onClick(View v){ for(int index = 0; index < mSelectedItems.size(); index++){ int selectedItemIndex = mSelectedItems.get(index); mEndPointList.removeViews(selectedItemIndex, 1); } mSelectedItems.clear(); mEndPointList.postInvalidate(); } }
This code is added as the onClickListener button for the Delete button. The code will execute without any problems, but the item will not be removed from the ListView. Does anyone have an idea why it is not working?
I think itβs fair to show my decision if someone else wonders how I actually did it. The selection is made in the OnItemClickListener list:
mEndPointList = ((ListView) findViewById(R.id.endpointList)); mEndPointList.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){ boolean found = false; int index = 0; while(!found && index >= 0 && index < mSelectedItems.size()){ if(mSelectedItems.get(index).intValue() == arg2){ found = true; mSelectedItems.remove(index); } index++; } if(!found){ mSelectedItems.add(new Integer(arg2)); } mSelectedItems.trimToSize(); } });
Elements are deleted as follows:
public class RemoveItemButtonHandler implements OnClickListener{ @Override public void onClick(View v){
Note that the DescendingComparator class is a custom class that implements the Comparator<Integer> interface.