您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。