根据导航栏类别筛选列表

时间:2017-02-26 20:44:10

标签: java android search navigation-drawer

这是我filter()中的RecyclerAdapter.class方法:

//Do search..
    public void filter(final String text) {
        // dispatch search to a different thread
        new Thread(new Runnable() {
        @Override
        public void run() {
            // clear the filteredList
            filteredList.clear();

            //if there is no search value load the whole list
            if (TextUtils.isEmpty(text)) {
                filteredList.addAll(chordsList);
            } else {
                //iterate through the original list and add to the filteredList
                for (Chord chord : chordsList) {
                    if (chord.getName().toLowerCase().contains(text.toLowerCase())) {
                        filteredList.add(chord);
                    }
                }
            }

            //set on UI thread
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    notifyDataSetChanged();
                }
            });

        }
    }).start();
}

它基于两个列表chordsList,其中包含整个列表,以及filteredList,顾名思义,它只包含那些包含text字符串的元素。

我的MainActivity就像这样调用它:

adapter = new RecyclerAdapter(this, chords);
    recyclerView.setAdapter(adapter);

    filteredList = new ArrayList<>();
    filteredList = adapter.getFilteredList();

然后在onCreateOptionsMenu(Menu menu)方法中:

final MenuItem searchItem = menu.findItem(R.id.action_search);
    searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
    setupSearch();

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.filter(newText);
            return true;
        }
    });

现在我需要做的是在onNavigationItemSelected(MenuItem item)方法中,当我点击特定类别时,我需要根据与String相关联的类别过滤列表。

public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    // TODO: da rivedere
    int id = item.getItemId();

    if (id == R.id.nav_c) {
    // String text = "c"
    // filteredList = all items containing c
    // inflate the recyclerView with the new filteredList
    }
    ...

如果你帮助我,那就太好了。

提前致谢

1 个答案:

答案 0 :(得分:2)

您的代码运行正常。 recyclerView.notifyDataSetChanged();方法的else部分中只缺少filter//if there is no search value load the whole list if (TextUtils.isEmpty(text)) { filteredList.addAll(chordsList); } else { //iterate through the original list and add to the filteredList for (Chord chord : chordsList) { if(chord.getName().toLowerCase().contains(text.toLowerCase())) { filteredList.add(chord); } } } recyclerView.notifyDataSetChanged(); 。写下这样的东西:

MyLocationTracking.TRACKING_FOLLOW

它肯定会起作用。让我知道是否有任何问题:)

谢谢