如何正确实现Filterable在BaseAdapter中搜索?

时间:2014-09-02 16:44:25

标签: android android-filter android-filterable

我在ListView中显示好友列表,并在TextWatcher上使用EditText设置以允许搜索。这有1个限制(我没有得到):输入一个字符正确过滤列表,删除一个字符但不做任何事情。当输入是正确的时,原始列表会正确显示为空,但Filter也应该在角色被删除时起作用,因为onTextChanged()被调用。我哪里错了?

类(BaseAdapter)字段:

private ArrayList<User> friends;
private ArrayList<User> originalFriendList;
//to keep track of the original list
this.originalFriendList = friends;

过滤类:

      private class FriendSearchFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        if (constraint != null && constraint.length() > 0) {

            ArrayList<User> filterList = new ArrayList<User>();

            for (User friend : friends) {
                if (StringUtils.containsIgnoreCase(friend.getLast_name(), constraint)
                        || StringUtils.containsIgnoreCase(friend.getFirst_name(), constraint)) {
                    filterList.add(friend);
                }
            }
            results.count = filterList.size();
            results.values = filterList;
        } else {
             // the input is empty
            results.count = originalFriendList.size();
            results.values = originalFriendList;
        }
        return results;
    }

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

TextWatcher

                 etSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int start,
                                      int before, int count) {
            /* no action required */
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int count, int after) {
            if(mFriendListFrag == null || !mFriendListFrag.equals(mFragAdapter.getItem(mViewPager.getCurrentItem())));
                mFriendListFrag = (FriendListFragment) mFragAdapter.getItem(mViewPager.getCurrentItem());
                mFLAdapter = (FriendListAdapter) mFriendListFrag.getListAdapter();
            mFLAdapter.getFilter().filter(charSequence.toString());
            Log.e("ON", "TEXT CHANGED");
        }

        @Override
        public void afterTextChanged(Editable editable) {
             /* no action required */
        }
    });

1 个答案:

答案 0 :(得分:0)

以防有人遇到类似的问题:我必须将约束与原始列表进行比较,而不是&#34;工作列表&#34;当我试图向后过滤时被覆盖:

        for (User friend : originalFriendList)

而不是

        for (User friend : friends)