大家好,我需要一些帮助。我正在尝试在我的项目中实现一个SearchView。但是我的项目包含一个带有自定义适配器的ListView。我已经搜索了许多网站,但是所有的示例都使用了ArrayAdapter。假设我有一个Employee类,它包含姓名和年龄字段。我该如何仅通过他们的姓名筛选员工。
public class MainActivity extends Activity implements SearchView.OnQueryTextListener
{
SearchView mSearchView;
ListView mListView;
//String mStrings[]= {"abc","def","efg","ghi","ijk","apple","agxhsdgc","abbbcc"};
ArrayList<Employee> emp_list=null;
EmployeeAdapter emp_adapter=null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSearchView=(SearchView) findViewById(R.id.searchView1);
mListView=(ListView) findViewById(R.id.listView1);
emp_list=new ArrayList<Employee>();
emp_list.add(new Employee("ABC", 24));
emp_list.add(new Employee("ACB", 24));
emp_list.add(new Employee("BVF", 28));
emp_list.add(new Employee("BRT", 28));
emp_list.add(new Employee("ANM", 23));
emp_adapter=new EmployeeAdapter(MainActivity.this, emp_list);
mListView.setAdapter(emp_adapter);
// mListView.setAdapter(new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1,
// mStrings));
mListView.setTextFilterEnabled(true);
setupSearchView();
}
private void setupSearchView()
{
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(true);
mSearchView.setQueryHint("Search Here");
}
@Override
public boolean onQueryTextChange(String newText)
{
if (TextUtils.isEmpty(newText.toString())) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText.toString());
}
return true;
}
@Override
public boolean onQueryTextSubmit(String query)
{
return false;
}
}
这是我的扩展了BaseAdapter的适配器类...
public class EmployeeAdapter extends BaseAdapter {
Context ctx;
ArrayList<Employee> emp_list;
LayoutInflater linf=null;
EmployeeHolder holder=null;
public EmployeeAdapter(Context ctx, ArrayList<Employee> emp_list) {
super();
this.ctx = ctx;
this.emp_list = emp_list;
linf=(LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public class EmployeeHolder
{
TextView name;
TextView age;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return emp_list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return emp_list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView==null)
{
convertView=linf.inflate(R.layout.row, parent, false);
holder=new EmployeeHolder();
holder.name=(TextView) convertView.findViewById(R.id.name);
holder.age=(TextView) convertView.findViewById(R.id.age);
convertView.setTag(holder);
}
else
{
holder=(EmployeeHolder) convertView.getTag();
}
Employee e=(Employee) getItem(position);
holder.name.setText(e.getName());
holder.age.setText(String.valueOf(e.getAge()));
return convertView;
}
}
提前致谢。