我通過擴展BaseAdapter並實現了Filterable接口創建了自定義適配器。此適配器用於在用戶輸入聯繫號碼或聯繫人姓名時向用戶建議電話號碼。 ArrayList<String> data
包含那些從手機中提取的「人名:號碼」模式的數據。刷新爲AutoCompleteTextView創建的自定義適配器中的數據
它的工作發現除了一個問題。如果我搜索以字母「A」開頭的聯繫人,它會正確顯示數據。如果我刪除它並再次鍵入「B」,它會顯示兩個聯繫人都以「A」和「B」開頭。我知道我必須在添加新數據之前用某種方法清除ArrayList<String> matchedResults
(檢查代碼),但是當我這樣做時,它給了我一個空的ArrayList。在哪一點我應該這樣做的方法或者是否有不同的解決方案?
這裏的代碼
public class AutoCompleteAdapter extends BaseAdapter implements Filterable {
private Context context;
private ArrayList<String> data;
private ArrayList<String> matchedResults = new ArrayList<String>();
public AutoCompleteAdapter(Context context, ArrayList<String> namesAndNumbers) {
this.context = context;
this.data = namesAndNumbers;
}
@Override
public int getCount() {
return matchedResults.size();
}
@Override
public String getItem(int position) {
return matchedResults.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_layout, parent, false);
TextView nameTextView = (TextView) view.findViewById(R.id.name);
TextView numberTextView = (TextView) view.findViewById(R.id.number);
String[] split = matchedResults.get(position).split(":");
nameTextView.setText(split[0]);
numberTextView.setText(split[1]);
return view;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint != null || constraint.length() != 0) {
for (String loop:data) {
int charSequenceSize = constraint.length();
if(onlyText(constraint.toString()) && !matchedResults.contains(loop)){
String[] split = loop.split(":");
String substring = split[0].substring(0, charSequenceSize);
if (substring.equalsIgnoreCase(constraint.toString())){
matchedResults.add(loop);
}
}else if(onlyNumbers(constraint.toString())){
String[] split = loop.split(":");
String substring = split[1].substring(0, charSequenceSize);
if (substring.equals(constraint.toString()) && !matchedResults.contains(loop)){
matchedResults.add(loop);
}
}
}
}
results.values = matchedResults;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
results.values = matchedResults;
notifyDataSetChanged();
}
};
}
public boolean onlyText(String text) {
boolean result = false;
if (Pattern.matches("[a-zA-Z ]+", text) && text.length() >= 1) {
result = true;
}
return result;
}
public boolean onlyNumbers(String text) {
boolean result = false;
if (Pattern.matches("[0-9+]+", text) && text.length() >= 1) {
result = true;
}
return result;
}
}
使用'SimpleCursorAdapter',並設置其'FilterQueryProvider',爲什麼在處理基於遊標的數據模型時使用'BaseAdapter'? – pskink