Android: Wrong item checked when filtering listview

前端 未结 3 802
挽巷
挽巷 2021-01-06 13:25

I\'m suffering from the same issue as this question: Wrong item checked when filtering ListView in android

As suggested in the above question, I have an Hashset hold

相关标签:
3条回答
  • 2021-01-06 13:33

    This is my solution:

    • To selecte an item in list view after filtering, at the beginning, I got wrong item because I used this:

      ItemData item = listItems.get(position);
      

    The correct way should be like this:

        ItemData item = (ItemData) parent.getItemAtPosition(position);
    
    • To delete an item after filtered, I have tried this:

      for(int i=0;i<listItems.size();i++){
          if(listItems.get(i).getItemID() == item.getItemID()){
              listItems.remove(i);
              myAdapter.notifyDataSetChanged();
         }
      }
      

    But that didn't worked because my custom adapter. In my custom adapter, to use filter, I have two listItems:

        ArrayList<ItemData> listItemsToShow = new ArrayList< ItemData >();
        ArrayList< ItemData > listItemsBackup = new ArrayList< ItemData >();
    

    So to delete an item, I added new method in my custom adapter:

        public void deleteItem(String itemID) {
        for (int i = 0; i < listItemsToShow.size(); i++) {
            if (listItemsToShow.get(i).getId().equals(itemID)) {
                listItemsToShow.remove(i);
                break;
            }
        }
    
        for (int i = 0; i < listItemsBackup.size(); i++) {
            if (listItemsBackup.get(i).getId().equals(itemID)) {
                listItemsBackup.remove(i);
                break;
            }
        }
    

    Finally to delete an item in list view:

        subjectBaseAdapter.deleteItem(subject.getId());
        subjectBaseAdapter.notifyDataSetChanged();
    

    Hope this help

    0 讨论(0)
  • 2021-01-06 13:38

    Solved the issue. As suggested in the question I added to mine, when you populate the checkboxes, the other List/Hashset should determine whether to mark item as checked or not.

    Using my code:

    //first you will need to get the current item ID
    String bookmarkID = cursor.getString(0);
    
    //Then, check if the current ID is in the selectedIds hash/list
    //If true - mark current item view as checked, else - uncheck.
            CheckedTextView markedItem = (CheckedTextView) row.findViewById(R.id.btitle);
            if (selectedIds.contains(new String(bookmarkID))) {
                markedItem.setChecked(true);
    
            } else {
                markedItem.setChecked(false);
    }
    

    Really hope this will help anyone! :)

    0 讨论(0)
  • 2021-01-06 13:45

    Could it be simply that you ListView does not know the data set changed? Call notifyDatSetChanged() on your adapter to let it know.

    my_adapter.notifyDataSetChanged();
    

    This will force a redraw of the list, with the updated data.

    0 讨论(0)
提交回复
热议问题