在字符串类型的ListView上实现SearchView,可以通过以下步骤完成:
以下是一个示例代码:
List<String> dataList = new ArrayList<>();
dataList.add("Apple");
dataList.add("Banana");
dataList.add("Orange");
// 添加更多的字符串...
public class MyAdapter extends BaseAdapter {
private List<String> dataList;
private LayoutInflater inflater;
public MyAdapter(Context context, List<String> dataList) {
this.dataList = dataList;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
}
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(dataList.get(position));
return convertView;
}
}
<SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
ListView listView = findViewById(R.id.listView);
SearchView searchView = findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
List<String> filteredList = new ArrayList<>();
for (String item : dataList) {
if (item.toLowerCase().contains(newText.toLowerCase())) {
filteredList.add(item);
}
}
((MyAdapter) listView.getAdapter()).setDataList(filteredList);
((MyAdapter) listView.getAdapter()).notifyDataSetChanged();
return true;
}
});
public void setDataList(List<String> dataList) {
this.dataList = dataList;
}
这样,当用户在SearchView中输入关键字时,ListView会根据关键字过滤并显示匹配的字符串项。
领取专属 10元无门槛券
手把手带您无忧上云