您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Android中,实现ListView的数据过滤功能可以通过以下几个步骤来完成:
public class CustomArrayAdapter extends ArrayAdapter<String> implements Filterable {
// ...
}
private Filter mFilter;
@Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
// 在这里实现数据过滤的逻辑
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// 在这里更新ListView的数据
}
};
}
return mFilter;
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<String> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
// 没有输入关键字,显示所有数据
filteredList.addAll(mOriginalList);
} else {
// 根据关键字过滤数据
String filterPattern = constraint.toString().toLowerCase().trim();
for (String item : mOriginalList) {
if (item.toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mFilteredList = (List<String>) results.values;
notifyDataSetChanged();
}
ListView listView = findViewById(R.id.list_view);
CustomArrayAdapter adapter = new CustomArrayAdapter(this, R.layout.list_item, dataList);
listView.setAdapter(adapter);
EditText editText = findViewById(R.id.edit_text);
editText.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) {
adapter.getFilter().filter(s);
}
@Override
public void afterTextChanged(Editable s) {
}
});
现在,当用户在EditText中输入关键字时,ListView会根据输入的关键字过滤数据。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。