无法使用自定义数组适配器从ListView过滤文本

时间:2013-06-27 09:00:08

标签: android listview search filter

我使用listview通过自定义适配器显示数据列表。

我有一个搜索文本框,我必须在列表视图中过滤文本。

代码:

        adapter = new ListCustomersAdapter(context, Customers);         
        lsCustomers = (ListView) findViewById(R.id.list_customers);
        lsCustomers.setTextFilterEnabled(true);

        edtSearch=(EditText)findViewById(R.id.edtSearch);
        edtSearch.addTextChangedListener(new TextWatcher() 
        {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text

            Log.d("","adapter: "+adapter);
            adapter.getFilter().filter(cs);                                 
            lsCustomers.setAdapter(adapter);
        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

和我的适配器类

 public class ListCustomersAdapter extends ArrayAdapter implements Filterable {

public Context ctx;
public String[] customers;
LayoutInflater mInflater;
 private boolean notifyChanged = true;

public ListCustomersAdapter(Context c,
        String[] Customers ){
    super(c, 0);
    mInflater = (LayoutInflater) c
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.ctx=c;
    this.customers=Customers;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return customers.length;
}

 public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        notifyChanged = true;
    }
@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View localView;
    if (convertView == null) {
        localView = mInflater
                .inflate(R.layout.list_view_layout, null);
    } else {
        localView = convertView;
    }

    TextView txtCustomername=(TextView)localView.findViewById(R.id.txtsimple_list);
    txtCustomername.setText(customers[position]);
    return txtCustomername;
}

}

但我仍然无法获得过滤后的文字。即使在文本框中输入搜索文本后,也会显示带有原始列表项的Listview

1 个答案:

答案 0 :(得分:0)

删除edtSe​​arch和带有侦听器的东西(addTextChangedListener),一切都会正常工作