我正在使用MultiAutoCompleteTextView
并在其上设置我自己的自定义适配器(BaseAdapter)。但每次我在MultiAutoCompleteTextView中写一些东西时,performFiltering
方法中的约束总是为我写的每个字符都获得空值。
以下是BaseAdapter类的代码:
public class ListItemAdapter extends BaseAdapter implements Filterable{
ArrayList<ListItem> listItems;
ArrayList<ListItem> suggestions = new ArrayList<>();
private Filter filter = new CustomFilter();
Context context;
LayoutInflater inflater;
public ListItemAdapter(ArrayList<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return listItems.size();
}
@Override
public Object getItem(int position) {
return listItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
v = inflater.inflate(R.layout.single_item, null);
TextView title = (TextView) v.findViewById(R.id.title);
title.setText(listItems.get(position).getTitle());
return v;
}
@Override
public Filter getFilter() {
return filter;
}
private class CustomFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
suggestions.clear();
Log.d("FILTERRES", ""+listItems.size() + ", " + constraint);
if(listItems != null && constraint != null) {
for(int i=0 ; i<listItems.size(); i++) {
if(listItems.get(i).getTitle().toLowerCase().contains(constraint)) {
suggestions.add(listItems.get(i));
}
}
}
FilterResults results = new FilterResults();
results.values = suggestions;
results.count = suggestions.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
以下是我如何将适配器设置为MultiAutoCompleteTextView:
MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.auto);
ListItemAdapter adapter = new ListItemAdapter(items, this);
textView.setThreshold(1);
textView.setAdapter(adapter);
我在这里做错了什么?
修改:
我将MultiAutoCompleteTextView
更改为AutoCompleteTextView
,现在它正常运行,是否有人知道如何使其适用于MultiAutoCompleteTextView?
答案 0 :(得分:3)
您需要setTokenizer()
到MultiAutoCompleteTextView
才能使其正常运行。
您可以使用 -
textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
如果您有任何特殊要求,即使您可以设置自己的自定义标记生成器,否则您可以使用CommaTokenizer
每次从下拉列表中选择任何选项时附加逗号(,)。