溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2020-09-15 08:47:05 來源:腳本之家 閱讀:358 作者:tonycheng93 欄目:移動開發(fā)

前言

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

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

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

分析

在查閱資料以后,發(fā)現(xiàn)其實Android中已經(jīng)幫我們實現(xiàn)了這個功能,如果你的ListView使用的是系統(tǒng)的ArrayAdapter,那么恭喜你,下面的事情就很簡單了,你只需要調(diào)用下面的代碼就可以實現(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) {
    //
  }
});

你沒看錯,就一行 mAdapter.getFilter().filter(cs);便可以實現(xiàn)這個搜索功能。不過我相信大多數(shù)Adapter都是自定義的,基于這個需求,我去分析了下ArrayAdapter,發(fā)現(xiàn)它實現(xiàn)了Filterable接口,那么接下來的事情就比較簡單了,就讓我們自定的Adapter也去實現(xiàn)Filterable這個接口,不久可以實現(xiàn)這個需求了嗎。下面貼出ArrayAdapter中顯示過濾功能的關(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();
      }
    }
  }
}

實現(xiàn)

首先寫了一個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;
  }
}

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

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

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

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

寫一個ArrayFilter類繼承自Filter類,我們需要兩個方法:

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

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

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

        ArrayList<User> values;
        synchronized (mLock) {//同步復(fù)制一個原始備份數(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對象
//          final String valueText = value.toString().toLowerCase();
          final String valueText = value.getName().toString().toLowerCase();//User對象的name屬性作為過濾的參數(shù)
          // First match against the whole, non-splitted value
          if (valueText.startsWith(prefixString) || valueText.indexOf(prefixString.toString()) != -1) {//第一個字符是否匹配
            newValues.add(value);//將這個item加入到數(shù)組對象中
          } 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;//此時的results就是過濾后的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;//此時,Adapter數(shù)據(jù)源就是過濾后的Results
      if (results.count > 0) {
        notifyDataSetChanged();//這個相當(dāng)于從mDatas中刪除了一些數(shù)據(jù),只是數(shù)據(jù)的變化,故使用notifyDataSetChanged()
      } else {
        /**
         * 數(shù)據(jù)容器變化 ----> notifyDataSetInValidated

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

特別說明

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

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

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

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

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

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

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

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

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

demo下載地址:EditSearch_jb51.rar

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI