我在这里假设您的对象是“汽车”
创建一个按名称过滤汽车并返回汽车列表的方法。
public static List<Car> filterCars(List<Car> cars, String searchText) {
List<Car> filteredCars = new ArrayList<>();
Car c;
for(int i = 0; i < cars.size(); i++) {
c = cars.get(i);
if (c.getCarName().toLowerCase().contains(searchText.trim().toLowerCase())) {
filteredCars.add(c);
}
}
return filteredCars;
}
此函数接受汽车列表作为输入和一个字符串以在汽车名称中搜索,并返回与汽车名称匹配的汽车列表和 searchText。
现在,在活动中,在您键入搜索文本的 EditText 中,添加 TextchangeListener。
yourEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
//grab your list to display in recyclerview.
// suppose it is carList
List<Car> newList = filterCars(YourListOfCar, editable.toString().trim());
// now this newList contains filtered car's list
// now send it to the adapter and call adapter function
// notifyDataSetChanged()
}
}
});