从自定义ListView中搜索联系人中的名称

时间:2014-07-26 07:29:40

标签: android

我有自定义ListView用于显示联系人(姓名,电话号码)。我成功获得联系人List.Now我正在尝试从列表中搜索名称。但是当我在EditText中给出Name时,app停止工作.Below是我使用的代码的一部分:

mList.setOnItemClickListener(this);

mList.setTextFilterEnabled(true);

inputSearch.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub
    adapter.getFilter().filter(s.toString());
}

@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
        int arg3) {
    // TODO Auto-generated method stub


}

@Override
public void afterTextChanged(Editable arg0) {
    // TODO Auto-generated method stub

}
});

自定义适配器中的代码

 public class MyListAdapter extends ArrayAdapter<ContactItems> implements Filterable{
private Filter nameFilter;

 public MyListAdapter(){
    super(MainActivity.this,R.layout.contact_view1,Items);
    }



@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
View v = convertView;
if(v==null){
    v = getLayoutInflater().inflate(R.layout.contact_view1, parent,false);
}

 ContactItems location = Items.get(position);

TextView nameTextView  = (TextView)v.findViewById(R.id.name);   
nameTextView.setText(location.getNames());

TextView numberTextView  = (TextView)v.findViewById(R.id.number);   
numberTextView.setText(location.getPhoneNumber());

ImageView mImageView = (ImageView)v.findViewById(R.id.face);    
mImageView.setImageResource(location.getImage());

return v;
}



@Override
public Filter getFilter() {
    // TODO Auto-generated method stub
    if(nameFilter==null)
    nameFilter = new NameFilter();

    return nameFilter;

}
}
NameFilter类中的代码

 public class NameFilter extends Filter {
 FilterResults results = new FilterResults();
 private List<ContactItems> nameList;
 private List<ContactItems> origNameList;
 @Override
 protected FilterResults performFiltering(CharSequence constraint) {
    // TODO Auto-generated method stub
    if (constraint == null || constraint.length() == 0) {
        // No filter implemented we return all the list
        results.values = origNameList;
        results.count = origNameList.size();}   else {
            // We perform filtering operation
            List<ContactItems> nNameList = new ArrayList<ContactItems>();

            for (ContactItems p : nameList) {
            if (p.getNames().toUpperCase().startsWith(constraint.toString().toUpperCase()))
            nNameList.add(p);
            }

            results.values = nNameList;
            results.count = nNameList.size();

            }
    return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
    // TODO Auto-generated method stub

}



}

有什么建议让它发挥作用吗?

0 个答案:

没有答案