android:在自定义列表视图中搜索

时间:2014-05-18 05:25:54

标签: android listview

我想用自定义数据填充列表视图,因此我创建了这个扩展BaseAdapter的类:

public class PersonAdapter extends BaseAdapter{

        List<Person> persons= getDataforListViewList();
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return persons.size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return persons.get(arg0);
        }

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

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
             if(arg1==null)
             {
                 LayoutInflater inflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                 arg1 = inflater.inflate(R.layout.listitem, arg2,false);
             }

             TextView Name = (TextView)arg1.findViewById(R.id.txtName);
             TextView PhoneNumber = (TextView)arg1.findViewById(R.id.txtPhone);

             Person person = persons.get(arg0);

             Name.setText(person.name);
             PhoneNumber.setText(person.phoneNumber);

             return arg1;
        }
}

然后我以这种方式填充我的列表视图:

PersonAdapter pe;
@Override
protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            pe=new PersonAdapter();
            ListView personListView = (ListView)findViewById(R.id.listView1);
            personListView.setAdapter(pe);          
            EditText inputSearch=(EditText) findViewById(R.id.inputSearch);
                    txtEditText.addTextChangedListener(new TextWatcher() {

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

        }


}

上面的代码工作正常,现在我想为我的listview添加搜索功能,我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用Filter类,它将使用edittext addTextChangedListener过滤listview中的每个数据。

 myFilter.addTextChangedListener(new TextWatcher() {

  public void afterTextChanged(Editable s) {
  }

  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  }

  public void onTextChanged(CharSequence s, int start, int before, int count) {
   dataAdapter.getFilter().filter(s.toString());
  }
  });

您需要创建一个扩展Filter的类。

有很好的例子here