Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

android - Filter list view from edit text

I have an edit text as a search bar and a list view that filters the text that I typed but unfortunately, it doesn't filter the list view. I have used an customize array adapter with object Friend. Friend object has name, address and phone number but I only want to filter its name. In my activity...

searchBarTextView.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    friendListAdapter.getFilter().filter(s);
}}

While in adapter...

    @Override
    public Filter getFilter() {
        Log.d(TAG, "begin getFilter");
        if(newFilter == null) {
            newFilter = new Filter() {
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    // TODO Auto-generated method stub
                    Log.d(TAG, "publishResults");
                    notifyDataSetChanged();
                }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                Log.d(TAG, "performFiltering");

                constraint = constraint.toString().toLowerCase();
                Log.d(TAG, "constraint : "+constraint);

                List<ChatObject> filteredFriendList = new LinkedList<ChatObject>();

                for(int i=0; i<friendList.size(); i++) {
                    Friend newFriend = friendList.get(i);
                    Log.d(TAG, "displayName : "+newFriend.getDisplayName().toLowerCase());
                    if(newFriend.getDisplayName().toLowerCase().contains(constraint)) {
                        Log.d(TAG, "equals : "+newFriend.getDisplayName());
                        filteredFriendList.add(newFriend);
                    }
                }

                FilterResults newFilterResults = new FilterResults();
                newFilterResults.count = filteredFriendList.size();
                newFilterResults.values = filteredFriendList;
                return newFilterResults;
            }
        };
    }
    Log.d(TAG, "end getFilter");
    return newFilter;
}

Could someone please help me how to correctly show the filtered array adapter? I think the notifyDataSetChanged is not invoked. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My problem is solved, found out that I have to override getCount() and getItem().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...