如何将搜索过滤器应用于具有分类过滤的回收器视图?



现在,我有一个回收器视图,其中包含两个类别的项目,以及活动的三个按钮,可以按"全部","设计类别"和"开发类别"过滤它们。单击按钮时,仅显示该类别的项目。我还有一个搜索栏,可以按名称过滤结果。在搜索栏中键入某些内容并筛选结果后,如果单击分类按钮,它将显示该类别的所有项目,而不仅仅是与搜索的名称匹配的项目。

我目前唯一的解决方案是在单击按钮时清除搜索栏,但我想这样做,以便在单击按钮后搜索栏过滤器仍然适用。

HomeActivity.Java:

public class HomeActivity implements RecyclerViewAdapter.RecyclerViewOnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
//other stuffs 
final Button allLessonsButton = (Button) findViewById(R.id.allLessonsButton);
allLessonsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onAllLessonsButtonTapped();
}});
final Button designLessonsButton = (Button) findViewById(R.id.designLessonsButton);
designLessonsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onDesignLessonsButtonTapped();
}});
final Button developmentLessonsButton = (Button) findViewById(R.id.developmentLessonsButton);
developmentLessonsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onDevelopmentLessonsButtonTapped();
}});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
}
setupRecyclerView();
}
private void setupRecyclerView() {
lessonRecyclerView = (RecyclerView) findViewById(R.id.lesson_recycler_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
lessonRecyclerView.setLayoutManager(linearLayoutManager);
}
private void onAllLessonsButtonTapped() {
currentLessons = allLessons;
adapter = new LessonRecyclerViewAdapter(this, currentLessons, this);
lessonRecyclerView.setAdapter(adapter);
}
private void onDesignLessonsButtonTapped() {
currentLessons = developmentLessons;
adapter = new LessonRecyclerViewAdapter(this, currentLessons, this);
lessonRecyclerView.setAdapter(adapter);
}
private void onDevelopmentLessonsButtonTapped() {
currentLessons = designLessons;
adapter = new LessonRecyclerViewAdapter(this, currentLessons, this);
lessonRecyclerView.setAdapter(adapter);
}

实质上,您的用户在显示列表之前有两种不同的方法来筛选列表。一方面,他们可以使用按钮选择类别;或者他们可以输入一些文本并通过搜索进行过滤。

现在的主要问题是辨别两种相互竞争的过滤方法。如果用户同时单击了类别并键入了查询,则我们不知道应该遵循哪种筛选方法。

在我看来,我们应该始终尊重最新的行动。

解决此问题的一种方法是,例如,让一个变量记录用户的最新操作。伪代码示例:

bool isSearching = false
when user types something:
isSearching = true
when a category is clicked:
isSearching = false
filtering:
if isSearching then:
filter based on query
else:
filter based on category

可以在不同的事件中实现此逻辑,例如 EditText onQueryTextChange 或 Button onClickListener 事件。

最新更新