我想在android应用程序中的列表上进行简单搜索:
app face image
这是我写的:
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList, R.layout.list_item, new String[]{"userId", "id"}, new int[]{R.id.userId, R.id.id});
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.this.adapter.getFilter().filter(s);
}
});
}
在“ onTextChanged”中,适配器下有错误,我认为是否有放置“ addTextChangedListener”的好地方!
答案 0 :(得分:2)
您的适配器使用Filterable实现,并在您的适配器中添加以下代码
//this method is for fillter list
@Override
public Filter getFilter() {
//filter have null value than return main list
if (userFilter == null)
userFilter = new UserFilter(this, mValues);
return userFilter;
}
private static class UserFilter extends Filter {
private final RecyclerViewAdapter adapter;
private final List<DataModel> originalList;
private final List<DataModel> filteredList;
private UserFilter(RecyclerViewAdapter adapter, List<DataModel> originalList) {
super();
this.adapter = adapter;
this.originalList = new ArrayList<>(originalList);
this.filteredList = new ArrayList<>();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
//first clear filter list
filteredList.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
//when Enterd no any string than all list add in filtered list
filteredList.addAll(originalList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final DataModel user : originalList) {
//check all list item with enterd string
if (user.getText().toLowerCase().contains(filterPattern)) {
//add match item in list
filteredList.add(user);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//when publish result first clear list
adapter.mFilteredList.clear();
//add all result value in list
adapter.mFilteredList.addAll((ArrayList<DataModel>) results.values);
adapter.notifyDataSetChanged();
}
}
并在您的活动中添加以下代码
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mAdapter.getFilter().filter(newText);
}
@Override
public void afterTextChanged(Editable s) {
}
});