要實現模糊查詢,在ListView中,你需要使用一個適配器來管理數據,并且根據輸入的查詢條件動態過濾數據。
以下是一個簡單的實現模糊查詢的示例:
下面是一個簡單的示例代碼:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private EditText editText;
private CustomAdapter adapter;
private List<String> dataList;
private List<String> filteredDataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
editText = findViewById(R.id.editText);
// 初始化數據列表
dataList = new ArrayList<>();
dataList.add("Apple");
dataList.add("Banana");
dataList.add("Cherry");
dataList.add("Grape");
dataList.add("Lemon");
dataList.add("Orange");
dataList.add("Peach");
dataList.add("Strawberry");
dataList.add("Watermelon");
filteredDataList = new ArrayList<>();
filteredDataList.addAll(dataList);
// 創建適配器并綁定數據
adapter = new CustomAdapter();
listView.setAdapter(adapter);
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) {}
});
}
private class CustomAdapter extends BaseAdapter implements Filterable {
private Filter filter;
@Override
public int getCount() {
return filteredDataList.size();
}
@Override
public Object getItem(int position) {
return filteredDataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(MainActivity.this).inflate(android.R.layout.simple_list_item_1, parent, false);
}
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(filteredDataList.get(position));
return convertView;
}
@Override
public Filter getFilter() {
if (filter == null) {
filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<String> filteredList = new ArrayList<>();
if (TextUtils.isEmpty(constraint)) {
filteredList.addAll(dataList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (String item : dataList) {
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) {
filteredDataList.clear();
filteredDataList.addAll((List<String>) results.values);
notifyDataSetChanged();
}
};
}
return filter;
}
}
}
在上述代碼中,用戶每次輸入查詢條件時,都會觸發EditText的onTextChanged()方法,然后通過調用適配器的getFilter().filter(s)方法來執行過濾操作。過濾結果會更新到適配器的filteredDataList列表中,并調用適配器的notifyDataSetChanged()方法刷新ListView。