CardListView 过滤器

CardListView filter

我正在使用 https://github.com/gabrielemariotti/cardslib 的 CardListView。 所以假设我有简单的 cardListView 及其适配器

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);

我想做的是根据CardHeader过滤我的cardListView。 CardArrayAdapter 具有方法

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

但我不明白它是如何过滤卡片的。在我的例子中,我把它放在

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

但是它没有在我的列表中找到任何卡片,无论是通过我在 card.setTitle() 中设置的文本还是通过 header.setTitle().

有人知道它是如何工作的吗? 非常感谢您花时间分享您的想法。

正如我在源代码中看到的那样,该库没有自定义过滤器的实现,因此首先您必须实现一个类似于此的自定义过滤器:

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();
    }
};

据我所知,在那之后你有 2 个选项:

1) 修改库源代码并将 CardArrayAdapterBaseCardArrayAdapter 中的 getFilter() 方法覆盖为 return 您的 customFilter[ 的一个实例=17=]

2) 直接在您的代码中实现过滤逻辑,并且仅在更新来自 onQueryTextChanged 的文本时更新您的适配器

您可以在此处找到代码参考:Custom getFilter in custom ArrayAdapter in android

arrayAdapter 实现 Filterable。例如,它与 Strings 或 int 一起工作得很好。 在您的情况下,您正在使用卡片。 在我看来,首先你应该重写卡片中的 toString() 方法。

ArrayAdapter 中的默认 getFilter() 方法使用 object.toString() 来过滤列表。

如果还不够,您可以实施自定义过滤器。

此致, 哈维尔