取一个 AutoCompleteTextView 并为其设置一个适配器。
然后在适配器中,
package com.example.sample.Adapters;
public class LocationAdapters extends ArrayAdapter<String> {
private MyFilter mFilter; // my personal filter: this is very important!!
ArrayList<Location> mObjects;
ArrayList<String> list = new ArrayList<String>();
ArrayList<Location> postCode = new ArrayList<Location>();
public LocationAdapters(Context context, int resource,
int textViewResourceId, ArrayList<Location> objects) {
super(context, resource, textViewResourceId);
mObjects = objects;
}
@Override
public int getCount() {
return list.size();
}
@Override
public String getItem(int position) {
try {
return list.get(position);
} catch (Exception e) {
notifyDataSetChanged();
return "";
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position < postCode.size()) {
view.setTag(postCode.get(position));
}
return view;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
if (position < postCode.size()) {
view.setTag(postCode.get(position));
}
return view;
}
@Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new MyFilter();
}
return mFilter;
}
// the trick is here!
private class MyFilter extends Filter {
ArrayList<String> tempResult = null;
// "constraint" is the string written by the user!
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// no constraint => nothing to return
if ((constraint == null) || (constraint.length() == 0)) {
synchronized (tempResult) {
tempResult = new ArrayList<String>();
postCode = new ArrayList<Location>();
results.values = tempResult;
results.count = tempResult.size();
}
} else {
String constr = constraint.toString();
tempResult = new ArrayList<String>();
postCode = new ArrayList<Location>();
for (Location location : mObjects) {
if (location.postcode.toLowerCase().contains(constr.toLowerCase()) || location.town.toLowerCase().contains(constr.toLowerCase())) {
String loc = location.town.toString();
if (loc.contains(",")) {
String[] splittedLoc = loc.split(",");
tempResult.add(splittedLoc[0] + ", " + location.county);
postCode.add(location);
} else {
tempResult.add(location.town + ", " + location.county);
postCode.add(location);
}
}
}
results.values = tempResult;
results.count = tempResult.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
list = (ArrayList<String>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
Log.e("notify", constraint.toString());
} else {
notifyDataSetInvalidated();
}
}
}
}