2

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

如何使用 SearchView 过滤 RecyclerView

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

  1. 如果我在 SearchView 中输入文本的速度过快,应用程序会崩溃并显示以下日志:

E/AndroidRuntime:致命异常:主进程:com.scherrer.robin.chvote,PID:28406 java.lang.NullPointerException:尝试调用虚拟方法'android.view.ViewGroup$LayoutParams android.view.View.getLayoutParams()'在 com.tonicartos.superslim.LayoutManager.fillNextSectionToEnd(LayoutManager.java:725) 的 com.tonicartos.superslim.LayoutManager 的 com.tonicartos.superslim.LayoutManager.getAnchorAtEnd(LayoutManager.java:1038) 的空对象引用上。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) 在 android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3283) 在 android.view.View.layout(View.java:16630) 在 android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) 在 android.widget.FrameLayout.onLayout(FrameLayout.java:273) 在 android.view.ViewGroup.layout(ViewGroup.java:5437) 在 android。 view.View.layout(View.java:16630) 在 android.view.ViewGroup.layout(ViewGroup.java:5437) 在 android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) 在 android.view.View.layout(View.java:16630) 在 android.view.ViewGroup.layout(ViewGroup.java:5437) 在 android.widget.FrameLayout.onLayout(FrameLayout.java:273) 在 android。 support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:122) 在 android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42) 在 android.support。design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1192) 在 android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:814) 在 android.view.View.layout(View.java:16630)在 android.view.ViewGroup.layout(ViewGroup.java:5437) 在 android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) 在 android.widget.FrameLayout.onLayout(FrameLayout.java:273) 在 android.view.View.layout(View.java:16630) 在 android.view.ViewGroup.layout(ViewGroup.java:5437) 在 android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743) 在 android。 widget.LinearLayout.layoutVertical(LinearLayout.java:1586) 在 android.widget.LinearLayout.onLayout(LinearLayout.java:1495) 在 android.view.View.layout(View.java:16630) 在 android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) 在 android.widget.FrameLayout.onLayout(FrameLayout.java:273) 在 android.view.ViewGroup.layout(ViewGroup.java:5437) 在 android。 view.View.layout(View.java:16630) 在 android.view.ViewGroup.layout(ViewGroup.java:5437) 在 android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743) 在 android.view.View.layout(View.java:16630) 在 android.widget.LinearLayout.onLayout(LinearLayout.java:1495) 在 android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586) 在 android. view.ViewGroup.layout(ViewGroup.java:5437) 在 android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) 在 android.widget.FrameLayout.onLayout(FrameLayout.java:273) 在 com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2678) 在 android.view.View.layout(View.java:16630) 在 android.view.ViewGroup.layout(ViewGroup.java :5437) 在 android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2171) 在 android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1931) 在 android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107) 在 android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013) 在 android.view.Choreographer$CallbackRecord.run(Choreographer.java:858) 在 android.view.Choreographer.doCallbacks(Choreographer.java:670) ) 在 android.view.Choreographer.doFrame(Choreographer.java:606) 在 android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844) 在 android.os.Handler。handleCallback(Handler.java:739) 在 android.os.Handler.dispatchMessage(Handler.java:95) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.jav

一开始我以为是因为filtermethod耗时太长而在完成之前再次执行,但写入日志后,我发现这不是导致问题的原因。

  1. 一旦我过滤某些内容并向下滚动,应用程序就会崩溃并显示以下日志:

致命异常:主进程:com.scherrer.robin.chvote,PID:473 java.lang.IndexOutOfBoundsException:无效项目位置 145(145)。项目数:20 在 android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617) 在 com.tonicartos 的 android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4622) .superslim.LayoutState.getView(LayoutState.java:

为了使 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);
}

}

带有 RecyclerView 的片段:

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;
    }
}

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

非常感谢任何帮助。

4

2 回答 2

1

我有一个超薄的recyclerview并尝试放置一个searchview(我在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
            }
        });

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

于 2016-06-29T11:23:24.643 回答
0

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

有人知道如何转换 LayoutManager 吗?

于 2016-06-29T20:34:08.710 回答