您好,登錄后才能下訂單哦!
在Android中,集成ListView控件的搜索功能可以通過以下幾個步驟實現:
在XML布局文件中添加一個SearchView控件,并將其放置在ActionBar或者其他合適的位置。例如:
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Search..." />
為了實現搜索功能,需要創建一個自定義的ArrayAdapter,該適配器繼承自BaseAdapter。在這個適配器中,需要重寫getFilter()方法來實現過濾功能。例如:
public class CustomArrayAdapter extends ArrayAdapter<String> {
private List<String> fullList;
private List<String> filteredList;
private Filter filter;
public CustomArrayAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
this.fullList = objects;
this.filteredList = objects;
}
@Override
public int getCount() {
return filteredList.size();
}
@Override
public String getItem(int position) {
return filteredList.get(position);
}
@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 (constraint == null || constraint.length() == 0) {
filteredList.addAll(fullList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (String item : fullList) {
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) {
filteredList = (List<String>) results.values;
notifyDataSetChanged();
}
};
}
return filter;
}
}
在Activity或Fragment中,初始化ListView和SearchView,并設置適配器。例如:
ListView listView = findViewById(R.id.listView);
SearchView searchView = findViewById(R.id.searchView);
List<String> data = new ArrayList<>();
// 添加數據到data列表中
CustomArrayAdapter adapter = new CustomArrayAdapter(this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
為SearchView設置一個OnQueryTextListener,當用戶輸入查詢時,調用適配器的getFilter().filter()方法進行過濾。例如:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return true;
}
});
現在,當用戶在SearchView中輸入查詢時,ListView將顯示與查詢匹配的項。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。