Android 在单击搜索视图图标之前,recyclerview 过滤器不显示任何项目

Android recyclerview filter showing no items until searchview icon is clicked

我有一个片段,我在其中进行网络调用并用卡片填充包含的回收器视图。现在我按照 this 向我的回收站视图添加了一个过滤器。现在问题出现在我做的适配器构造函数中

this.storeLists = new ArrayList<>(storeLists);

在我单击搜索视图图标并开始输入内容之前,我的片段中的列表已填充但不显示任何项目。之后,即使我关闭搜索视图,列表也会保留。

我尝试将上面的行更改为

this.storeLists = storeLists;

当我删除搜索查询时,已删除的项目不会重新显示。因此,如果我在我的回收站视图列表中搜索不存在的内容,我的回收站视图中将不会显示任何内容。

我想要的是,当我打开该片段时,我会看到结果,然后当我单击搜索图标并开始输入时,过滤器会如上文 link 所示工作。

编辑:

Here is my adapter and here 是我的调用片段。

您正在使用 this.storeLists = new ArrayList<>(storeLists);因此 notifyDatasetChanged 将无法工作,因为您正在使用一个新列表。

但是您不应该更改它,因为您需要保留 storeLists,因为它包含您的完整数据。您可以做的是在您的适配器中创建如下方法

 public void setList(ArrayList<StoreList> mList){
   this.storeList = mList;
   notifyDataSetChanged();
 }

下载数据并添加到商店列表后,在片段中按如下方式调用 setList 方法

 mAdapter.setList(storeList);

同时删除 storeReq 方法中的 mAdapter.notifyDataSetChanged(),因为它什么都不做。

经过一些尝试和尝试,我找到了以动画效果为代价的解决方案。现在,代码段只需像这样重置适配器即可工作:

@Override
public boolean onQueryTextChange(String newText) {
    Log.d(TAG,newText);
    searchStoreList = storeList;
    final List<StoreList> filteredModelList = filter(searchStoreList, newText);
    //((RVStoreAdapter) mAdapter).animateTo(filteredModelList);
    //The above commented line is the old code. Following is how to reset the adapter!
    mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new RVStoreAdapter(getActivity(),storeList,session.getLat(),session.getLongi());
    mRecyclerView.setAdapter(mAdapter);
    mRecyclerView.scrollToPosition(0);
    return true;
}

动画现在非常突然,但解决方案会在相应更改搜索查询时重置列表。