我的应用程序中有一个EditText和一个ListView,我的ListView显示联系人列表。我想使用EditText过滤ListView。我在Google上搜索了很多,并找到了一些例子,但都没有对我起作用,这是我的代码
我的自定义适配器
public class ContactListAdapter extends ArrayAdapter {
private final Activity activity;
private final List<ContactStock> stocks;
private ArrayList<ContactStock> arraylist;
public ContactListAdapter(Activity activity, List<ContactStock> objects) {
super(activity, R.layout.listview_detail, objects);
this.activity = activity;
this.stocks = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView = convertView;
ContactStockView sv = null;
if (rowView == null) {
// Get a new instance of the row layout view
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(
R.layout.listview_detail, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
sv = new ContactStockView();
sv.name = (TextView) rowView.findViewById(R.id.textView1);
sv.number = (TextView) rowView.findViewById(R.id.textView2);
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(sv);
} else {
sv = (ContactStockView) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
ContactStock currentStock = (ContactStock) stocks.get(position);
sv.name.setText(currentStock.getName());
sv.number.setText(currentStock.getNumber());
// TODO Auto-generated method stub
return rowView;
}
protected static class ContactStockView {
protected TextView name;
protected TextView number;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
stocks.clear();
if (charText.length() == 0) {
stocks.addAll(arraylist);
} else {
for (ContactStock cs : arraylist) {
if (cs.getName().contains(charText)) {
stocks.add(cs);
}
}
}
notifyDataSetChanged();
}
}
主类EditText的代码为
edittext = (EditText)findViewById(R.id.editText1);
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
//MainActivity.this.adapt.getFilter().filter(s);
String searchString=edittext.getText().toString();
adapt.filter(searchString);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
没有自定义适配器时,可以使用getfilter()方法进行过滤。但我不知道如何使用自定义适配器进行过滤。如果有帮助将不胜感激。提前致谢。