How to implement getFilter on a BaseAdapter?

前端 未结 7 839
半阙折子戏
半阙折子戏 2020-12-06 03:55

I am trying to implement a getFilter() on a base adapter to filter out search results on a List. Is there any example of how to implement a getFilter()?

MainActivity

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 04:05

    General procedure

    1. Enable text filtering on your ListView
    2. Change your baseadapter to store two copies of the list, one original, one filtered.
    3. Change all access references in your BaseAdapter to refer to the Filtered list, not the original.
    4. Implement your Filter function in BaseAdapter.

    Step 1:
    listview.setTextFilterEnabled(true);

    Step 2:

    public class AppInfoAdapter extends BaseAdapter implements Filterable{
        private List mListAppInfo;
        private List mListAppInfoFiltered;
    
    public AppInfoAdapter(Context c, List list, PackageManager pm) {
        mContext = c;
        mListAppInfo = list;
        mPackManager = pm;
        mPackManagerFiltered = pm; //added line
    }
    

    Step 3:

    public int getCount() {
        return mListAppInfoFiltered.size();
    }
    public Object getItem(int position) {
        return mListAppInfoFiltered.get(position);
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        // get the selected entry
        ApplicationInfo entry = (ApplicationInfo) mListAppInfoFiltered.get(position);
    

    }

    Step 4: I am not sure what type your list is, so assuming a list of String:

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                if (constraint == null || constraint.length() == 0) {
                    //no search, so just return all the data
                    results.count = mListAppInfo.size();
                    results.values = mListAppInfo;
                } else {//do the search
                    List resultsData = new ArrayList<>();
                    String searchStr = constraint.toString().toUpperCase();
                    for (String s : mListAppInfo)
                            if (s.toUpperCase().contains(searchStr)) resultsData.add(s);
                        results.count = resultsData.size();
                        results.values = resultsData;
                    }
                    return results;
                }
    
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    mListAppInfoFiltered = (ArrayList) results.values;
                    notifyDataSetChanged();
                }
            };
        }
    }
    

提交回复
热议问题