![](/img/trans.png)
[英]AutoCompleteTextView custom ArrayAdapter & Filter performance
[英]AutoCompleteTextView with custom ArrayAdapter and Filter
當我嘗試從LogCat篩選AutoCompleteTextView中的結果時遇到問題,我知道篩選已正確執行,但沒有刷新視圖:/我是否忘記了任何建議或幫助?
這是過濾器的源代碼。
@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;
}
缺少的部分是我需要從過濾器設置新值,所以我只是簡單地改變了
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();
}
}
另一個更新 - 在輸入和刪除搜索文本框中的所有字符時,很快就會崩潰newValues.size()或newValues.get(i)上的應用程序,因為newValues可能為null。 所以,這是你應該使用的代碼:
@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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.