我正在开发一个应用程序,有一个list列表,在列表上面有一个 edittext编辑框,当我在编辑框中输入内容时,得不到和输入的信息相符合的结果。请问错误出现在哪儿?以下是 Activity和Adapter的代码。谢谢!
Activity
public class ListFilterActivity extends ListActivity{
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_filter);
list = getListView();
list.isTextFilterEnabled();
// final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, android.R.id.text1,
// getModel());
final CustomAdapter adapter = new CustomAdapter(ListFilterActivity.this, getModel());
setListAdapter(adapter);
EditText filterEditText = (EditText) findViewById(R.id.filterText);
filterEditText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString());
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
private ArrayList<String> getModel() {
ArrayList<String> list = new ArrayList<String>();
list.add("Linux");
list.add("Windows7");
list.add("Suse");
list.add("Eclipse");
list.add("Ubuntu");
list.add("Solaris");
list.add("Android");
list.add("Ayes");
list.add("iPhone");
return list;
}
}
** Adapter **
public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<String> names;
private LayoutInflater mInflater;
private TextView txt;
public CustomAdapter(Context context, ArrayList<String> names) {
super(context, R.layout.row, names);
this.context = context;
this.names = names;
mInflater = LayoutInflater.from(context);
}
public Filter getFilter() {
if(newFilter == null) {
newFilter = new Filter() {
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// TODO Auto-generated method stub
Log.d("TAG", "publishResults");
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
ArrayList<String> i = new ArrayList<String>();
if (prefix!= null && prefix.toString().length() > 0) {
for (int index = 0; index < names.size(); index++) {
String si = names.get(index);
if(si.compareTo(prefix.toString()) == 0){
i.add(si);
}
}
results.values = i;
results.count = i.size();
}
else{
synchronized (names){
results.values = names;
results.count = names.size();
}
}
return results;
}
};
}
// Log.d("TAG", "end getFilter");
return newFilter;
}
@Override
public String getItem(int position) {
return super.getItem(position);
}
@Override
public int getCount() {
return super.getCount();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if(rowView == null) {
rowView = mInflater.inflate(R.layout.row, null);
txt = (TextView)rowView.findViewById(R.id.text1);
}
else {
rowView.getTag();
}
txt.setText(names.get(position));
return rowView;
}
}