当前位置: 首页 > 知识库问答 >
问题:

过滤器回收器使用搜索视图查看

姜业
2023-03-14

我使用SearchView过滤我的应用程序的RecyclerView,就像这篇文章中描述的一样:

如何使用SearchView筛选RecyclerView

一开始一切看起来都很好,我可以根据需要过滤RecyclerView,但是经过一些尝试,出现了两个问题:

  1. 如果我在SearchView中输入文本太快,应用程序会崩溃,并出现以下日志:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.scherrer.robin.chvote, PID: 28406 java.lang.NullPointerException: 尝试调用虚拟方法 'android.view.ViewGroup$LayoutParams android.view.View.getLayoutParams()' on a null object reference at com.tonicartos.superslim.LayoutManager.getAnchorAtEnd(LayoutManager.java:1038) at com.tonicartos.superslim.LayoutManager.fillNextSectionToEnd(LayoutManager.java:725) atcom.tonicartos.superslim.LayoutManager.layoutChildren(LayoutManager.java:1369) at com.tonicartos.superslim.LayoutManager.onLayoutChildren(LayoutManager.java:276) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2906) at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3283) at android.view.View.layout(View.java:16630) atandroid.view.ViewGroup.layout(ViewGroup.java:5437) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) at android.widget.FrameLayout.onLayout(FrameLayout.java:273) at android.view.View.layout(View.java:16630) at android.view.ViewGroup.layout(ViewGroup.java:5437) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) at android.widget.FrameLayout.onLayout(FrameLayout.java:273) at android.view.View.layout(View.java:16630) at android.view.view.layout(View.java:16630) atandroid.view.ViewGroup.layout(ViewGroup.java:5437) at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:122) at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42) at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1192) at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:814) atandroid.view.view.view.layout(View.java:16630) at android.view.ViewGroup.layout(ViewGroup.java:5437) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) at android.widget.FrameLayout.onLayout(FrameLayout.java:273) at android.view.layout(View.java:16630) at android.view.viewgroup.layout(ViewGroup.java:5437) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586) atandroid.widget.LinearLayout.onLayout(LinearLayout.java:1495) at android.view.View.layout(View.java:16630) at android.view.ViewGroup.layout(ViewGroup.java:5437) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) at android.widget.FrameLayout.onLayout(FrameLayout.java:273) at android.view.View.layout(View.java:16630) at android.view.ViewGroup.layout(ViewGroup.java:5437) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743) atandroid.widget.LinearLayout.layoutVertical(LinearLayout.java:1586) at android.widget.LinearLayout.onLayout(LinearLayout.java:1495) at android.view.View.layout(View.java:16630) at android.view.ViewGroup.layout(ViewGroup.java:5437) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) at android.widget.FrameLayout.onLayout(FrameLayout.java:273) at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2678) atandroid.view.view.view.layout(View.java:16630) at android.view.ViewGroup.layout(ViewGroup.java:5437) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2171) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1931) at android.view.View.ViewRootImpl.doTraversal(ViewRootImpl.java:1107) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858) atandroid.view.Choreographer.doCallbacks(Choreographer.java:670) at android.view.Choreographer.doFrame(Choreographer.java:606) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844) at android.os.handler.handleCallback(Handler.java:739) at android.os.handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.jav

起初我认为,出现错误是因为filtermethod花费了太长时间,并且在完成之前再次执行,但通过写入日志,我发现这并不是问题的原因。

致命异常: 主进程: com.scherrer.robin.chvote, PID: 473 java.lang.IndexOutOfBoundsException: Invalid item position 145(145).Item count:20 at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4622) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617) at com.tonicartos.superslim.LayoutState.getView(LayoutState.java:48) at com.tonicartos.superslim.LayoutManager.getHeaderOrFirstViewForSection(LayoutManager.java:1242) at com.tonicartos.superslim.LayoutManager.fillToEnd(LayoutManager.java:840) atcom.tonicartos.superslim.LayoutManager.fillUntil(LayoutManager.java:908) at com.tonicartos.superslim.LayoutManager.scrollVerticallyBy(LayoutManager.java:361) at android.support.v7.widget.RecyclerView.scrollByInternal(RecyclerView.java:1529) at android.support.v7.widget.RecyclerView.onTouchEvent(RecyclerView.java:2486) at android.view.View.Touch dispatchEvent(View.java:9294) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2547) atandroid.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2240) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553) at android.view.viewgroup.dispatchTouchEvent(ViewGroup.java:2254) at android.view.viewgroup.dispatchTransformedTouchEvent(ViewGroup.java:2553) at android.view.view.dispatchTouchEvent(ViewGroup.java:2254) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553) atandroid.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254) at android.view.viewgroup.dispatchTransformedTouchEvent(ViewGroup.java:2553) at android.view.view.dispatchTouchEvent(ViewGroup.java:2254) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553) atandroid.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254) at android.view.viewgroup.dispatchTransformedTouchEvent(ViewGroup.java:2553) at android.view.view.dispatchTouchEvent(ViewGroup.java:2254) at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2403) atcom.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737) at android.app.Activity.dispatchTouchEvent(Activity.java:2765) at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60) at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60) at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2364) atandroid.view.view.dispatchPointerEvent(View.java:9514) at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4230) at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4096) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3642) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3695) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3661) at android.viewandroid.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3787) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3669) at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3844) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3642) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3695) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3661) at android.view.View.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3661) atandroid.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3669) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3642) at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5922) at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5896) at android.view.View

为了使RecyclerView中的标题项具有粘性,我使用了一个名为Super-SLiM的库

适配器:

public class RfrdAdapter extends RecyclerView.Adapter<RfrdViewHolder> {
private final LayoutInflater mInflater;
private final List<AdapterBaseRow> mModels;

private static final int VIEW_TYPE_HEADER = 0x01;
private static final int VIEW_TYPE_RFRD_OPEN = 0x02;
private static final int VIEW_TYPE_RFRD_PAST = 0x03;

public RfrdAdapter(Context context, List<AdapterBaseRow> models) {
    this.mInflater = LayoutInflater.from(context);
    this.mModels = new ArrayList<>(models);
}

@Override
public RfrdViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View itemView = null;

    switch (viewType) {
        case VIEW_TYPE_HEADER:
            itemView = mInflater.inflate(R.layout.rfrd_list_title, parent, false);
            break;
        case VIEW_TYPE_RFRD_OPEN:
            itemView = mInflater.inflate(R.layout.open_referendum, parent, false);
            break;
        case VIEW_TYPE_RFRD_PAST:
            itemView = mInflater.inflate(R.layout.past_referendum, parent, false);
            break;
        default:
            Log.e("CHVote", "viewType not specified");
            break;
    }

    return new RfrdViewHolder(itemView);
}

@Override
public int getItemViewType(int position) {
    int itemViewType = 0;

    if (mModels.get(position) instanceof AdapterRowHeader) {
        itemViewType = VIEW_TYPE_HEADER;
    } else if (mModels.get(position) instanceof AdapterRowRfrdPast) {
        itemViewType = VIEW_TYPE_RFRD_PAST;
    } else if (mModels.get(position) instanceof AdapterRowRfrdOpen) {
        itemViewType = VIEW_TYPE_RFRD_OPEN;
    }

    return itemViewType;
}

@Override
public void onBindViewHolder(RfrdViewHolder holder, int position) {
    final AdapterBaseRow model = mModels.get(position);
    final View itemView = holder.itemView;
    final LayoutManager.LayoutParams params;

    holder.bind(model);

    params = (LayoutManager.LayoutParams) itemView.getLayoutParams();
    params.setSlm(LinearSLM.ID);
    params.setFirstPosition(model.sectionFirstPosition);
    itemView.setLayoutParams(params);
}

@Override
public int getItemCount() {
    return mModels.size();
}

public void animateTo(List<AdapterBaseRow> models) {
    applyAndAnimateRemovals(models);
    applyAndAnimateAdditions(models);
    applyAndAnimateMovedItems(models);

    Log.d("tag", "Finshed filtering");
}

private void applyAndAnimateRemovals(List<AdapterBaseRow> newModels) {
    for (int i = mModels.size() - 1; i >= 0; i--) {
        final AdapterBaseRow model = mModels.get(i);
        if (!newModels.contains(model)) {
            removeItem(i);
        }
    }
}

private void applyAndAnimateAdditions(List<AdapterBaseRow> newModels) {
    for (int i = 0, count = newModels.size(); i < count; i++) {
        final AdapterBaseRow model = newModels.get(i);
        if (!mModels.contains(model)) {
            addItem(i, model);
        }
    }
}

private void applyAndAnimateMovedItems(List<AdapterBaseRow> newModels) {
    for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
        final AdapterBaseRow model = newModels.get(toPosition);
        final int fromPosition = mModels.indexOf(model);
        if (fromPosition >= 0 && fromPosition != toPosition) {
            moveItem(fromPosition, toPosition);
        }
    }
}

public AdapterBaseRow removeItem(int position) {
    final AdapterBaseRow model = mModels.remove(position);
    notifyItemRemoved(position);
    return model;
}

public void addItem(int position, AdapterBaseRow model) {
    mModels.add(position, model);
    notifyItemInserted(position);
}

public void moveItem(int fromPosition, int toPosition) {
    final AdapterBaseRow model = mModels.remove(fromPosition);
    mModels.add(toPosition, model);
    notifyItemMoved(fromPosition, toPosition);
}

}

带有RecyclView的片段:

public class MainFragment extends Fragment implements SearchView.OnQueryTextListener {

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    private RecyclerView mRecyclerView;
    private RfrdAdapter mAdapter;
    private List<AdapterBaseRow> mModels;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_main, container, false);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.lvRef);

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);

        this.mRecyclerView.setLayoutManager(new LayoutManager(getActivity()));

        AdapterData adapterData = new AdapterData();

        this.mModels = adapterData.getRfrdData();
        mAdapter = new RfrdAdapter(getActivity(), mModels);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main, menu);

        final MenuItem item = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(this);
    }

    @Override
    public boolean onQueryTextChange(String query) {
        final List<AdapterBaseRow> filteredModelList = filter(mModels, query);

        Log.d("tag","Started filtering");

        mAdapter.animateTo(filteredModelList);
        mRecyclerView.scrollToPosition(0);

        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    private List<AdapterBaseRow> filter(List<AdapterBaseRow> models, String query) {
        final List<AdapterBaseRow> filteredModelList = new ArrayList<>();
        final ArrayList<String> searchableTxt = new ArrayList<String>();

        query = query.toLowerCase();

        for (AdapterBaseRow model : models) {
            if (model instanceof AdapterRowHeader) {
                final String searchTxtVotingDateHeader = ((AdapterRowHeader) model).getVotingDateTxt().toLowerCase();
                searchableTxt.add(searchTxtVotingDateHeader);
            } else if (model instanceof AdapterRowRfrdOpen) {
                final String searchTxtTitleRfrdOpen = ((AdapterRowRfrdOpen) model).getOpenRfrd().getTitle().toLowerCase();
                searchableTxt.add(searchTxtTitleRfrdOpen);
                final String searchTxtVotingDateRfrdOpen = ((AdapterRowRfrdOpen) model).getOpenRfrd().getVotingDateTxt().toLowerCase();
                searchableTxt.add(searchTxtVotingDateRfrdOpen);
            } else if (model instanceof AdapterRowRfrdPast) {
                final String searchTxtTitleRfrdPast = ((AdapterRowRfrdPast) model).getPastRfrd().getTitle().toLowerCase();
                searchableTxt.add(searchTxtTitleRfrdPast);
                final String searchTxtVotingDateRfrdPast = ((AdapterRowRfrdPast) model).getPastRfrd().getVotingDateTxt().toLowerCase();
                searchableTxt.add(searchTxtVotingDateRfrdPast);
            }

            for (String sTxt : searchableTxt) {
                if (sTxt.contains(query)) {
                    filteredModelList.add(model);
                    break;
                }
            }

            searchableTxt.clear();
        }
        return filteredModelList;
    }
}

我看了这里的许多线程,尝试了许多不同的组合,但似乎不能解决这个问题。

任何帮助都非常感谢。

共有2个答案

应翰飞
2023-03-14

经过一些测试,我发现问题在于SuperLim库需要一个定制的LayoutManager,但过滤仅适用于LinearLayoutManager。

有人知道如何转换LayoutManager吗?

林富
2023-03-14

我有一个带有superslim的recyclerview,并尝试放置一个searchview(我在片段up recyclerview中使用edittext)

我有很多问题过滤结果,标题错误等。最后,我创建了一个不优雅的解决方案,但工作正常且易于实现:

首先,你必须让你的recyclerview与你的适配器和superslim一起工作(你可以看到所有的条目都与你的头粘在一起)

其次,我的解决方案是用过滤后的结果重新创建数据(数组),并用一些逻辑重新构建适配器:

//event on write in filter field
buscador.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                //get the word...
                String text = buscador.getText().toString().toLowerCase(Locale.getDefault());


                if(text.isEmpty()){
                    //if text is empty  we load all results (no filter results)
                    actividades.clear();
                    actividades.addAll(actividadescopia); //actividadescopia is a clone of actividades(data for populate recyclerview, and all results without filtered)
                } else{
                    //if no empty (searching a word)...
                    //we create a array for results finds...
                    ArrayList<ActividadBean> result = new ArrayList<>();
                    text = text.toLowerCase();
                    for(ActividadBean item: actividadescopia){
                        if(item.getTitulo()!=null) {
                            if (item.getTitulo().toLowerCase().contains(text)) {
                            //...add to results if find coincidence
                                result.add(item);
                            }
                        }
                    }
                    //populate array with the results
                    actividades.clear();
                    actividades.addAll(result);
                }

                if(actividades.size()>0) { //if we have results...
                    //...inicialize adapter and set in recyclerview
                    mAdapter = new ListaBusquedaAdapter(getActivity(), mHeaderDisplay, actividades);
                    mRecyclerView.setAdapter(mAdapter);
                    //...and set recyclerview visible for see results (see below)
                    mRecyclerView.setVisibility(View.VISIBLE);
                }else{
                    //..if we haven't results we hide the recyclerview for show that nothing is finding with filtered word
                    mRecyclerView.setVisibility(View.GONE);
                }

            }
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub
            }
            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
        });

我希望它能帮助你(对不起,我不是英语母语)

 类似资料:
  • 我正试图在我的RecyclerView中实现搜索过滤器,就像在这篇文章中一样 我现在面临的主要问题是setOnQueryTextListener,在我的活动中:“在QueryTextListenerAdapter上找不到符号类”。这可能是我确实需要创造的东西,也可能是我没有在我的活动中实现的东西。它只是MainActivity扩展了AppCompatActivity。 我的 onCreateMen

  • 我正试图在我的RecyclerView中实现搜索过滤器,就像在这篇文章中一样 我已经对它进行了调试,它确实按照预期过滤了项目,但列表在应用程序中似乎没有改变。一、 E:我过滤一个名字,有7个结果,在屏幕上是原始列表。 我的 onCreateMenu活动选项是: 我的适配器如下所示: 我忘了什么? 提前致谢!

  • 我试图在Fragment中实现一个带有建议(过滤器)的SearchView,但是我没有成功。我尝试了几乎所有的教程,但没有一个对我有效。我将感激任何帮助。谢谢你 可扩展置标语言... 碎片 适配器

  • 我使用此解决方案来过滤我的。使用该解决方案,我能够在键入时获得结果。但是当我清除搜索小部件时,我没有得到完整的列表,而是得到了空的。 这就是我的结果。https://imgur.com/nwyetEd 这是我的 这是我的 这是我使用过滤器的< code >活动 有人能帮助我吗?

  • 当我尝试将Image URL解析到ImageView中时,回收器视图不显示,活动为空。我正在使用Picasso将图像加载到适配器类中的onBinfViewHolder方法中。这是相关代码 代表: } RepRvAdapter: } 解析JSON数据的方法: 现在,我有一行解析图像URL的代码被注释掉了。行取消注释后,活动将不再显示。如何获取要在ImageView中解析和显示的图像url?我认为这可

  • Android通用搜索功能似乎有很好的系统支持,除了语音搜索之外,还可以显示搜索建议,如最近的查询建议和自定义建议。 此框架要求声明搜索活动。该活动以意向获取查询,并将搜索结果呈现给列表视图。 我对此有两个问题: 1-我想在当前活动中进行搜索(我在应用程序栏上有一个搜索视图)。那么,该活动是否会重新启动?那会很奇怪。我应该发送到不可见的活动并获取结果吗?这可能吗? 2-我可以使用RecyclerV