Anand
Anand

Reputation: 1959

Searchable spinner not working

I have a spinner with search functionality. The spinner has items like "hello-there".ie; A name followed by a hyphen and then another name. The spinner search is working fine if we search for the keyword left of the hyphen. But it will show empty if we search the keyword right of the hyphen. Is there any library that fulfills my requirement? Or how to implement this? Iam currently using this library com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1

Upvotes: 4

Views: 1325

Answers (1)

maheryhaja
maheryhaja

Reputation: 1687

The problem is that the filter used in this library is the default filter of ArrayAdapter class.

Your best option is to create a custom filterable adapter for the spinner data. Take a look at this question

to resolve your hyphen problem: the filter will look like

 private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();

        FilterResults results = new FilterResults();

        final List<String> list = originalData;

        int count = list.size();
        final ArrayList<String> nlist = new ArrayList<String>(count);

        String filterableString ;

        for (int i = 0; i < count; i++) {
            filterableString = list.get(i);
            if (filterableString.toLowerCase().contains(filterString)) {
                nlist.add(filterableString);
            }
        }

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

        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<String>) results.values;
        notifyDataSetChanged();
    }

}
}  

filterableString.toLowerCase().contains(filterString) should do the trick. However, if you want more elaborate way where the prefix should be the bigining of the left or right hyphen text. You can proceed like this:

for (int i = 0; i < count; i++) {
        filterableString = list.get(i);
         String[] parts = filterableString.split("-")
       if(parts[0].startsWith(filterString)||parts[1].startsWith(filterString){
            nlist.add(filterableString);
        }
    }

Upvotes: 3

Related Questions