ListView Not Updating After Filtering

前端 未结 5 1923
清酒与你
清酒与你 2020-12-31 06:06

I have a ListView (with setTextFilterEnabled(true)) and a custom adapter (extends ArrayAdapter) which I update from the main UI thread whenever a new item is added/inserted.

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 06:56

    First of all I would like to mention, that @jhie's answer is very good. However those facts did not really solve my problem. But with the help of knowledge of how the internally used mechanism worked, I could write it my own filtering function:

    public ArrayList listArray = new ArrayList<>();
    public ArrayList tempListArray = new ArrayList<>();
    public ArrayAdapter tempAdapter;
    public String currentFilter;
    

    in onCreate:

    // Fill my ORIGINAL listArray;
    listArray.add("Cookies are delicious.");
    
    // After adding everything to listArray, I add everything to tempListArray
    for (String element : listArray){
        tempListArray.add(element);
    }
    
    // Setting up the Adapter...
    tempAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, tempListArray);
    myListView.setAdapter(tempAdapter);
    

    Filtering:

    // Defining filter functions
    public void customFilterList(String filter){
            tempListArray.clear();
            for (String item : listArray){
                if (item.toLowerCase().contains(filter.toLowerCase())){
                    tempListArray.add(item);
                }
            }
            currentFilter = filter;
            tempAdapter.notifyDataSetChanged();
        }
        public void updateList(){
            customFilterList(currentFilter);
        }
    

    I used it for implementing a search function into my list.

    The big advantage: You have much more filtering power: at customFilterList() you can easily implement the usage of Regular Expressions or use it as a case sensitive filter.

    Instead of notifyDataSetChanged you would call updateList() .

    Instead of myListView.getFilter().filter('filter text') you would call customFilterList('filter text')

    At the moment this is only working with one ListView. Maybe - with a bit of work - you could implement this as a Custom Array Adapter.

提交回复
热议问题