我有一个扩展ArrayAdapter的自定义ArrayAdapter:
class MyAdapter extends ArrayAdapter<String> implements Filterable{
Context context;
String [] data;
MyAdapter (Context context, String [] data) {
super(context, R.layout.item_news, R.id.text, data);
this.context = context;
this.data = data;
}
class MyViewHolder {
TextView text;
MyViewHolder(View view) {
text = (TextView) view.findViewById(R.id.text);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder myViewHolder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.mylayout, parent, false);
myViewHolder = new MyViewHolder(row);
row.setTag(myViewHolder);
}
else
myViewHolder = (MyViewHolder) row.getTag();
myViewHolder.text.setText(data[position]);
return row;
}
现在我想让我的Array Filterable。我尝试过:
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
ArrayList<String> tempList = new ArrayList<String>();
if (constraint != null && data!= null) {
String filterString = constraint.toString().toLowerCase();
for (int i=0; i< data.length; i++) {
String item = data[i];
if (item.toLowerCase().contains(filterString)) {
tempList.add(item);
}
filterResults.values = tempList;
filterResults.count = tempList.size();
}
return filterResults;
}
return null;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence contraint, FilterResults results) {
data = (String[]) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
@Override
public Filter getFilter() {
return myFilter;
}
但这不起作用:当我打电话时:
adapter.getFilter().filter(filter);
未应用过滤器。 你能帮我么?我想通过用户提供的字符串过滤内容。 PS如果您发现我的基座适配器有问题,请随时给我任何建议。