Search code examples
androidlistviewandroid-filter

CardListView filter


I'm using CardListView from https://github.com/gabrielemariotti/cardslib. So assume I have simple cardListView with its adapter

CardListView cardListView = (CardListView) findViewById(R.id.card_list);
ArrayList cards = new ArrayList<>();

Card card = new Card(this);
card.setTitle("card text");
CardHeader header = new CardHeader(this);
header.setTitle("card header");
card.addCardHeader(header);

cards.add(card);
CardArrayAdapter adapter = new CardArrayAdapter(this, cards);
cardListView.setAdapter(adapter);

What I want to do is to filter my cardListView according to CardHeader. The CardArrayAdapter has the method

adapter.getFilter().filter("some text")

But I don't get the idea how it filters cards. In my case, I placed it in

@Override
public boolean onQueryTextChange(String s) {
    adapter.getFilter().filter(s);
    return true;
}

But it isn't finding any cards in my list, neither by the text I have set in card.setTitle() nor by header.setTitle().

Does anyone know how that works at all? I really appreciate your taking the time to share your thoughts.


Solution

  • As I can see in the source code, the library doesn't have an implementation for custom filters so first of all you must implement a custom filter similar to this one:

    Filter cardFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults filterResults = new FilterResults();   
            ArrayList<Card> tempList = new ArrayList<Card>();
            // Where constraint is the value you're filtering against and
            // cards is the original list of elements
            if(constraint != null && cards!=null) {
                // Iterate over the cards list and add the wanted
                // items to the tempList
    
                filterResults.values = tempList;
                filterResults.count = tempList.size();
            }
            return filterResults;
        }
    
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            // Update your adapter here and notify
            cardArrayAdapter.addAll(results.values);
            cardArrayAdapter.notifyDataSetChanged();
        }
    };
    

    After that you have 2 options as far as I can see:

    1) Modify the library source code and override the getFilter() method in the CardArrayAdapter or BaseCardArrayAdapter to return an instance of your customFilter

    2) Implement the filtering logic directly in your code and only update your adapter when the text from onQueryTextChanged is updated

    Here you can find a reference for the code: Custom getFilter in custom ArrayAdapter in android