2011-12-23 118 views
1

我有一個問題,當我想從LogCat過濾AutoCompleteTextView中的結果我知道過濾執行正確,但它不刷新視圖:/我忘記了一些建議或幫助?AutoCompleteTextView與自定義ArrayAdapter和篩選器

以下是過濾器的源代碼。

@Override 
public Filter getFilter() { 
    Filter myFilter = new Filter() { 

     @Override 
     protected FilterResults performFiltering(CharSequence constraint) { 
      Log.i(TAG, "Perform filtering with constraint: " + constraint.toString()); 
      List<String> resultsSuggestions = new ArrayList<String>(); 
      Log.i(TAG, "COUNT: " + getCount()); 
      for (int i = 0; i < getCount(); i++) { 
       if(getItem(i).getSuggestionValue().startsWith(constraint.toString())){ 
        Log.i(TAG, "ADDED"); 
        resultsSuggestions.add(getItem(i).getSuggestionValue()); 
       } 
      } 
      FilterResults results = new FilterResults(); 
      results.values = resultsSuggestions; 
      results.count = resultsSuggestions.size(); 
      return results; 
     } 

     @Override 
     protected void publishResults(CharSequence constraint, FilterResults results) { 
      if (results != null && results.count > 0) { 
       notifyDataSetChanged(); 
      } else { 
       notifyDataSetInvalidated(); 
      } 
     } 
    }; 
    return myFilter; 
} 

回答

2

缺少的部分是,我需要從過濾器設置新的價值觀,所以我只是簡單地改變了

publushResults(); 

,現在它的工作。正確的代碼在下面。

@Override 
    @SuppressWarnings("unchecked") 
    protected void publishResults(CharSequence constraint, FilterResults results) { 
     clear(); 
     ArrayList<Suggestions> newValues = (ArrayList<Suggestions>) results.values; 
     for (int i = 0; i < newValues.size(); i++) { 
      add(newValues.get(i)); 
     } 
     if(results.count>0){ 
      notifyDataSetChanged(); 
     } else{ 
      notifyDataSetInvalidated(); 
     } 
    } 
1

另一個更新 - 在輸入和搜索文本框很快刪除所有文字崩潰的newValues.size()或newValues.get(i)申請作爲newValues可能爲空。所以,這裏是你應該使用的代碼:

@Override 
    @SuppressWarnings("unchecked") 
    protected void publishResults(CharSequence constraint, FilterResults results) { 
     clear(); 
     ArrayList<Suggestions> newValues = (ArrayList<Suggestions>) results.values; 
     if(newValues !=null) { 
      for (int i = 0; i < newValues.size(); i++) { 
       add(newValues.get(i)); 
      } 
      if(results.count>0){ 
       notifyDataSetChanged(); 
      } else{ 
       notifyDataSetInvalidated(); 
     } 
    } 
+0

你能告訴我我和你的代碼有什麼區別嗎? – Robert 2012-02-27 19:48:07

+1

@羅伯特,你的不是抄襲,他是。 – Skyline 2014-07-29 09:06:03

相關問題