最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android ListView用EditText實(shí)現(xiàn)搜索功能效果

 更新時(shí)間:2017年03月25日 11:34:07   作者:tonycheng93  
本篇文章主要介紹了Android ListView用EditText實(shí)現(xiàn)搜索功能效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。

前言

最近在開(kāi)發(fā)一個(gè)IM項(xiàng)目的時(shí)候有一個(gè)需求就是,好友搜索功能。即在EditText中輸入好友名字,ListView列表中動(dòng)態(tài)展示刷選的好友列表。我把這個(gè)功能抽取出來(lái)了,先貼一下效果圖:

分析

在查閱資料以后,發(fā)現(xiàn)其實(shí)Android中已經(jīng)幫我們實(shí)現(xiàn)了這個(gè)功能,如果你的ListView使用的是系統(tǒng)的ArrayAdapter,那么恭喜你,下面的事情就很簡(jiǎn)單了,你只需要調(diào)用下面的代碼就可以實(shí)現(xiàn)了:   

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) {
    //
  }
});

你沒(méi)看錯(cuò),就一行 mAdapter.getFilter().filter(cs);便可以實(shí)現(xiàn)這個(gè)搜索功能。不過(guò)我相信大多數(shù)Adapter都是自定義的,基于這個(gè)需求,我去分析了下ArrayAdapter,發(fā)現(xiàn)它實(shí)現(xiàn)了Filterable接口,那么接下來(lái)的事情就比較簡(jiǎn)單了,就讓我們自定的Adapter也去實(shí)現(xiàn)Filterable這個(gè)接口,不久可以實(shí)現(xiàn)這個(gè)需求了嗎。下面貼出ArrayAdapter中顯示過(guò)濾功能的關(guān)鍵代碼: 

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();
      }
    }
  }
}

實(shí)現(xiàn)

首先寫(xiě)了一個(gè)Model(User)模擬數(shù)據(jù)

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;
  }
}

自定義一個(gè)Adapter(UserAdapter)繼承自BaseAdapter,實(shí)現(xiàn)了Filterable接口,Adapter一些常見(jiàn)的處理,我都去掉了,這里主要講講Filterable這個(gè)接口。
 

/**
   * Contains the list of objects that represent the data of this Adapter.
   * Adapter數(shù)據(jù)源
   */
  private List<User> mDatas;

 //過(guò)濾相關(guān)
  /**
   * This lock is also used by the filter
   * (see {@link #getFilter()} to make a synchronized copy of
   * the original array of data.
   * 過(guò)濾器上的鎖可以同步復(fù)制原始數(shù)據(jù)。
   * 
   */
  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.
  //對(duì)象數(shù)組的備份,當(dāng)調(diào)用ArrayFilter的時(shí)候初始化和使用。此時(shí),對(duì)象數(shù)組只包含已經(jīng)過(guò)濾的數(shù)據(jù)。
  private ArrayList<User> mOriginalValues;
  private ArrayFilter mFilter;

 @Override
  public Filter getFilter() {
    if (mFilter == null) {
      mFilter = new ArrayFilter();
    }
    return mFilter;
  }

寫(xiě)一個(gè)ArrayFilter類(lèi)繼承自Filter類(lèi),我們需要兩個(gè)方法:

//執(zhí)行過(guò)濾的方法
 protected FilterResults performFiltering(CharSequence prefix);
//得到過(guò)濾結(jié)果
 protected void publishResults(CharSequence prefix, FilterResults results);

貼上完整的代碼,注釋已經(jīng)寫(xiě)的不能再詳細(xì)了

 /**
   * 過(guò)濾數(shù)據(jù)的類(lèi)
   */
  /**
   * <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/>
   * 一個(gè)帶有首字母約束的數(shù)組過(guò)濾器,每一項(xiàng)不是以該首字母開(kāi)頭的都會(huì)被移除該list。
   */
  private class ArrayFilter extends Filter {
    //執(zhí)行刷選
    @Override
    protected FilterResults performFiltering(CharSequence prefix) {
      FilterResults results = new FilterResults();//過(guò)濾的結(jié)果
      //原始數(shù)據(jù)備份為空時(shí),上鎖,同步復(fù)制原始數(shù)據(jù)
      if (mOriginalValues == null) {
        synchronized (mLock) {
          mOriginalValues = new ArrayList<>(mDatas);
        }
      }
      //當(dāng)首字母為空時(shí)
      if (prefix == null || prefix.length() == 0) {
        ArrayList<User> list;
        synchronized (mLock) {//同步復(fù)制一個(gè)原始備份數(shù)據(jù)
          list = new ArrayList<>(mOriginalValues);
        }
        results.values = list;
        results.count = list.size();//此時(shí)返回的results就是原始的數(shù)據(jù),不進(jìn)行過(guò)濾
      } else {
        String prefixString = prefix.toString().toLowerCase();//轉(zhuǎn)化為小寫(xiě)

        ArrayList<User> values;
        synchronized (mLock) {//同步復(fù)制一個(gè)原始備份數(shù)據(jù)
          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對(duì)象
//          final String valueText = value.toString().toLowerCase();
          final String valueText = value.getName().toString().toLowerCase();//User對(duì)象的name屬性作為過(guò)濾的參數(shù)
          // First match against the whole, non-splitted value
          if (valueText.startsWith(prefixString) || valueText.indexOf(prefixString.toString()) != -1) {//第一個(gè)字符是否匹配
            newValues.add(value);//將這個(gè)item加入到數(shù)組對(duì)象中
          } 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循環(huán)
                newValues.add(value);
                break;
              }
            }
          }
        }
        results.values = newValues;//此時(shí)的results就是過(guò)濾后的List<User>數(shù)組
        results.count = newValues.size();
      }
      return results;
    }

    //刷選結(jié)果
    @Override
    protected void publishResults(CharSequence prefix, FilterResults results) {
      //noinspection unchecked
      mDatas = (List<User>) results.values;//此時(shí),Adapter數(shù)據(jù)源就是過(guò)濾后的Results
      if (results.count > 0) {
        notifyDataSetChanged();//這個(gè)相當(dāng)于從mDatas中刪除了一些數(shù)據(jù),只是數(shù)據(jù)的變化,故使用notifyDataSetChanged()
      } else {
        /**
         * 數(shù)據(jù)容器變化 ----> notifyDataSetInValidated

         容器中的數(shù)據(jù)變化 ----> notifyDataSetChanged
         */
        notifyDataSetInvalidated();//當(dāng)results.count<=0時(shí),此時(shí)數(shù)據(jù)源就是重新new出來(lái)的,說(shuō)明原始的數(shù)據(jù)源已經(jīng)失效了
      }
    }
  }

特別說(shuō)明

//User對(duì)象的name屬性作為過(guò)濾的參數(shù)
 final String valueText = value.getName().toString().toLowerCase();

這個(gè)地方是,你要進(jìn)行搜索的關(guān)鍵字,比如我這里使用的是User對(duì)象的Name屬性,就是把用戶名當(dāng)作關(guān)鍵字來(lái)進(jìn)行過(guò)濾篩選的。這里要根據(jù)你自己的具體邏輯來(lái)進(jìn)行設(shè)置。

復(fù)制代碼 代碼如下:

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

在這里進(jìn)行關(guān)鍵字匹配,如果你只想使用第一個(gè)字符匹配,那么你只需要使用這行代碼就可以了:

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

如果你的需求是只要輸入的字符出現(xiàn)在ListView列表中,那么該item就要顯示出來(lái),那么你就需要這行代碼了:

//你輸入的關(guān)鍵字包含在了某個(gè)item中,位置不做考慮,即可以不是第一個(gè)字符 
valueText.indexOf(prefixString.toString()) != -1

這樣就完成了一個(gè)EditText + ListView實(shí)現(xiàn)搜索的功能。我在demo中用兩種方法實(shí)現(xiàn)了這一效果。第一種是系統(tǒng)的ArrayAdapter實(shí)現(xiàn),第二種是自定義Adapter實(shí)現(xiàn)。

demo下載地址:EditSearch_jb51.rar

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

敖汉旗| 通州市| 揭西县| 贡觉县| 都江堰市| 九寨沟县| 农安县| 裕民县| 宁陵县| 龙山县| 台中市| 长宁县| 普兰县| 武城县| 来凤县| 甘洛县| 大冶市| 黑龙江省| 遂昌县| 元氏县| 师宗县| 资源县| 普洱| 延安市| 浏阳市| 南木林县| 体育| 前郭尔| 镇江市| 蛟河市| 荥阳市| 庆城县| 庄河市| 珠海市| 桓仁| 乐业县| 麻栗坡县| 大兴区| 奇台县| 罗山县| 西乡县|