Android ListView用EditText实现搜索功能

前言

最近在开发一个IM项目的时候有一个需求就是,好友搜索功能。即在EditText中输入好友名字,ListView列表中动态展示刷选的好友列表。我把这个功能抽取出来了,先贴一下效果图: ![](http://i.imgur.com/cpfPXLo.gif)![](http://i.imgur.com/WsOSkQd.png)

分析

在查阅资料以后,发现其实Android中已经帮我们实现了这个功能,如果你的ListView使用的是系统的ArrayAdapter,那么恭喜你,下面的事情就很简单了,你只需要调用下面的代码就可以实现了:    
searchEdittext.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user change the text
        mAdapter.getFilter().filter(cs);
    }
    
    @Override
    public void beforeTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        //
    }
    
    @Override
    public void afterTextChanged(Editable arg0) {
        //
    }
});

你没看错,就一行 mAdapter.getFilter().filter(cs);便可以实现这个搜索功能。不过我相信大多数Adapter都是自定义的,基于这个需求,我去分析了下ArrayAdapter,发现它实现了Filterable接口,那么接下来的事情就比较简单了,就让我们自定的Adapter也去实现Filterable这个接口,不久可以实现这个需求了吗。下面贴出ArrayAdapter中显示过滤功能的关键代码:  
public class ArrayAdapter<T> extends BaseAdapter implements Filterable {
    /**
     * Contains the list of objects that represent the data of this ArrayAdapter.
     * The content of this list is referred to as "the array" in the documentation.
     */
    private List<T> mObjects;
    
    /**
     * Lock used to modify the content of {@link #mObjects}. Any write operation
     * performed on the array should be synchronized on this lock. This lock is also
     * used by the filter (see {@link #getFilter()} to make a synchronized copy of
     * the original array of data.
     */
    private final Object mLock = new Object();
    
    // A copy of the original mObjects array, initialized from and then used instead as soon as
    // the mFilter ArrayFilter is used. mObjects will then only contain the filtered values.
    private ArrayList<T> mOriginalValues;
    private ArrayFilter mFilter;
    
    ...
    
    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new ArrayFilter();
        }
        return mFilter;
    }

    /**
     * <p>An array filter constrains the content of the array adapter with
     * a prefix. Each item that does not start with the supplied prefix
     * is removed from the list.</p>
     */
    private class ArrayFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();

            if (mOriginalValues == null) {
                synchronized (mLock) {
                    mOriginalValues = new ArrayList<T>(mObjects);
                }
            }

            if (prefix == null || prefix.length() == 0) {
                ArrayList<T> list;
                synchronized (mLock) {
                    list = new ArrayList<T>(mOriginalValues);
                }
                results.values = list;
                results.count = list.size();
            } else {
                String prefixString = prefix.toString().toLowerCase();

                ArrayList<T> values;
                synchronized (mLock) {
                    values = new ArrayList<T>(mOriginalValues);
                }

                final int count = values.size();
                final ArrayList<T> newValues = new ArrayList<T>();

                for (int i = 0; i < count; i++) {
                    final T value = values.get(i);
                    final String valueText = value.toString().toLowerCase();

                    // First match against the whole, non-splitted value
                    if (valueText.startsWith(prefixString)) {
                        newValues.add(value);
                    } else {
                        final String[] words = valueText.split(" ");
                        final int wordCount = words.length;

                        // Start at index 0, in case valueText starts with space(s)
                        for (int k = 0; k < wordCount; k++) {
                            if (words[k].startsWith(prefixString)) {
                                newValues.add(value);
                                break;
                            }
                        }
                    }
                }

                results.values = newValues;
                results.count = newValues.size();
            }

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            //noinspection unchecked
            mObjects = (List<T>) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

实现

  • 首先写了一个Model(User)模拟数据
public class User {
    private int avatarResId;
    private String name;

    public User(int avatarResId, String name) {
        this.avatarResId = avatarResId;
        this.name = name;
    }

    public int getAvatarResId() {
        return avatarResId;
    }

    public void setAvatarResId(int avatarResId) {
        this.avatarResId = avatarResId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • 自定义一个Adapter(UserAdapter)继承自BaseAdapter,实现了Filterable接口,Adapter一些常见的处理,我都去掉了,这里主要讲讲Filterable这个接口。
 /**
     * Contains the list of objects that represent the data of this Adapter.
     * Adapter数据源
     */
    private List<User> mDatas;

  //过滤相关
    /**
     * This lock is also used by the filter
     * (see {@link #getFilter()} to make a synchronized copy of
     * the original array of data.
     * 过滤器上的锁可以同步复制原始数据。
     * 
     */
    private final Object mLock = new Object();

    // A copy of the original mObjects array, initialized from and then used instead as soon as
    // the mFilter ArrayFilter is used. mObjects will then only contain the filtered values.
    //对象数组的备份,当调用ArrayFilter的时候初始化和使用。此时,对象数组只包含已经过滤的数据。
    private ArrayList<User> mOriginalValues;
    private ArrayFilter mFilter;

 @Override
    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new ArrayFilter();
        }
        return mFilter;
    }
  • 写一个ArrayFilter类继承自Filter类,我们需要两个方法:
//执行过滤的方法
 protected FilterResults performFiltering(CharSequence prefix);
//得到过滤结果
 protected void publishResults(CharSequence prefix, FilterResults results);
  • 贴上完整的代码,注释已经写的不能再详细了
 /**
     * 过滤数据的类
     */
    /**
     * <p>An array filter constrains the content of the array adapter with
     * a prefix. Each item that does not start with the supplied prefix
     * is removed from the list.</p>
     * <p/>
     * 一个带有首字母约束的数组过滤器,每一项不是以该首字母开头的都会被移除该list。
     */
    private class ArrayFilter extends Filter {
        //执行刷选
        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();//过滤的结果
            //原始数据备份为空时,上锁,同步复制原始数据
            if (mOriginalValues == null) {
                synchronized (mLock) {
                    mOriginalValues = new ArrayList<>(mDatas);
                }
            }
            //当首字母为空时
            if (prefix == null || prefix.length() == 0) {
                ArrayList<User> list;
                synchronized (mLock) {//同步复制一个原始备份数据
                    list = new ArrayList<>(mOriginalValues);
                }
                results.values = list;
                results.count = list.size();//此时返回的results就是原始的数据,不进行过滤
            } else {
                String prefixString = prefix.toString().toLowerCase();//转化为小写

                ArrayList<User> values;
                synchronized (mLock) {//同步复制一个原始备份数据
                    values = new ArrayList<>(mOriginalValues);
                }
                final int count = values.size();
                final ArrayList<User> newValues = new ArrayList<>();

                for (int i = 0; i < count; i++) {
                    final User value = values.get(i);//从List<User>中拿到User对象
//                    final String valueText = value.toString().toLowerCase();
                    final String valueText = value.getName().toString().toLowerCase();//User对象的name属性作为过滤的参数
                    // First match against the whole, non-splitted value
                    if (valueText.startsWith(prefixString) || valueText.indexOf(prefixString.toString()) != -1) {//第一个字符是否匹配
                        newValues.add(value);//将这个item加入到数组对象中
                    } else {//处理首字符是空格
                        final String[] words = valueText.split(" ");
                        final int wordCount = words.length;

                        // Start at index 0, in case valueText starts with space(s)
                        for (int k = 0; k < wordCount; k++) {
                            if (words[k].startsWith(prefixString)) {//一旦找到匹配的就break,跳出for循环
                                newValues.add(value);
                                break;
                            }
                        }
                    }
                }
                results.values = newValues;//此时的results就是过滤后的List<User>数组
                results.count = newValues.size();
            }
            return results;
        }

        //刷选结果
        @Override
        protected void publishResults(CharSequence prefix, FilterResults results) {
            //noinspection unchecked
            mDatas = (List<User>) results.values;//此时,Adapter数据源就是过滤后的Results
            if (results.count > 0) {
                notifyDataSetChanged();//这个相当于从mDatas中删除了一些数据,只是数据的变化,故使用notifyDataSetChanged()
            } else {
                /**
                 * 数据容器变化 ----> notifyDataSetInValidated

                 容器中的数据变化  ---->  notifyDataSetChanged
                 */
                notifyDataSetInvalidated();//当results.count<=0时,此时数据源就是重新new出来的,说明原始的数据源已经失效了
            }
        }
    }

特别说明

//User对象的name属性作为过滤的参数
  final String valueText = value.getName().toString().toLowerCase();

这个地方是,你要进行搜索的关键字,比如我这里使用的是User对象的Name属性,就是把用户名当作关键字来进行过滤筛选的。这里要根据你自己的具体逻辑来进行设置。

 if (valueText.startsWith(prefixString) || valueText.indexOf(prefixString.toString()) != -1)

在这里进行关键字匹配,如果你只想使用第一个字符匹配,那么你只需要使用这行代码就可以了:

//首字符匹配
valueText.startsWith(prefixString)

如果你的需求是只要输入的字符出现在ListView列表中,那么该item就要显示出来,那么你就需要这行代码了:

//你输入的关键字包含在了某个item中,位置不做考虑,即可以不是第一个字符  
valueText.indexOf(prefixString.toString()) != -1

这样就完成了一个EditText + ListView实现搜索的功能。我在demo中用两种方法实现了这一效果。第一种是系统的ArrayAdapter实现,第二种是自定义Adapter实现。有需要的可以看看,我已经把Demo上传到了我的github上面。
Github地址:https://github.com/tonycheng93/EditSearch
博客地址:http://tonycheng93.github.io/

posted @ 2016-04-26 17:18  tonycheng93  阅读(5249)  评论(3编辑  收藏  举报