Creating getFilter for BaseAdapter for Object titles?

这一生的挚爱 提交于 2020-01-07 05:48:08

问题


I'm creating a ListView using CardsUI and I'm planning to create a search using getFilter(). The cards each have a title accessible via getTitle(). Every example of getFilter I've seen has been for just Strings. Does anybody know of any good examples (or can provide a good example) of how I'd adapt getFilter() to match against the titles returned by getTitle() and return the list of objects with a title matching the given string?

Thanks.


回答1:


I've Implemented this kind of feature in my application.

A brief explanation. Implement your own class that extends Filter, like the next class:

private class PlanetFilter extends Filter {
@Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        // We implement here the filter logic
        if (constraint == null || constraint.length() == 0) {
            // No filter implemented we return all the list
            results.values = planetList;
            results.count = planetList.size();
        }
        else {
            // We perform filtering operation
            List<Planet> nPlanetList = new ArrayList<Planet>();

            for (Planet p : planetList) {
                if (p.getName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
                    nPlanetList.add(p);
            }

            results.values = nPlanetList;
            results.count = nPlanetList.size();

        }
        return results;
    }
}

In your base adapter implements Filterable interface and it has to implement getFilter() method:

@Override
public Filter getFilter() {
    if (planetFilter == null)
        planetFilter = new PlanetFilter();

    return planetFilter;
}

And to tie all together, use textWatcher on your edittext, where you enter the text.

editTxt.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        System.out.println("Text ["+s+"]");
        aAdpt.getFilter().filter(s.toString());                           
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
    }
});

That code is taken from the next tutorial.



来源:https://stackoverflow.com/questions/17328955/creating-getfilter-for-baseadapter-for-object-titles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!