如何正确过滤带有searchview的RecyclerView?

时间:2018-12-04 16:34:44

标签: android android-recyclerview searchview

大家好,我已经在RecyclerView中实现了SearchView,但是当我搜索角色名称时,它并没有搜索任何名称,因此我遵循了tutorial

  

在实现了recyclerview的适配器类下面   易碎

公共类LeovegasAdapter扩展了RecyclerView.Adapter实现了Filterable {

private List<Hero> heros;
private List<Hero> filtarableList;

public LeovegasAdapter(List<Hero> heros) {
    this.heros = heros;
    filtarableList = filtarableList;
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.hero_list, parent, false);

    return new CustomViewHolder(itemView);
}

@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
    Hero hero = heros.get(position);
    holder.heroId.setText(hero.getId());
    holder.heroName.setText(hero.getName());

}

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


@Override
public Filter getFilter() {

    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {

            String charString = charSequence.toString();

            if (charString.isEmpty()) {

                filtarableList = heros;
            } else {

                ArrayList<Hero> filteredList = new ArrayList<>();

                for (Hero hero : heros) {

                    if (hero.getId().toLowerCase().contains(charString) || hero.getName().toLowerCase().contains(charString)) {

                        filteredList.add(hero);
                    }
                }

                filtarableList = filteredList;
            }

            FilterResults filterResults = new FilterResults();
            filterResults.values = filtarableList;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filtarableList = (List<Hero>) results.values;
            notifyDataSetChanged();
        }
    };
}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    public TextView heroId, heroName;

    public CustomViewHolder(View view) {
        super(view);
        heroId = (TextView) view.findViewById(R.id.heroId);
        heroName = (TextView) view.findViewById(R.id.heroName);


    }
}

}

在我的MainActivity.java下面

public class MainActivity extends AppCompatActivity {


   public LeovegasAdapter leovegasAdapter;


    public static final String publicKey = "4089ee37331d8211b080b047c58f6970";
    public static final String privateKey = "18ccbcb58fdd12c22821f8b633a06f2b433d16c3";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




        LeoVegasInterface leoVegasInterface = LeoVegasClient.getApiService();
        String ts = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String hash = Hasher.md5(ts + privateKey + publicKey);
        Call<LeoVegas> callHeroes = leoVegasInterface.getHeroes(ts, publicKey, hash);

        callHeroes.enqueue(new Callback<LeoVegas>() {
            @Override
            public void onResponse(Call<LeoVegas> call, Response<LeoVegas> response) {
                LeoVegas leoVegas = response.body();
                Data data = leoVegas.getData();
                Hero[] heroes = data.getResults();
                RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
                leovegasAdapter = new LeovegasAdapter(Arrays.asList(heroes));
                RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getApplicationContext());
                recyclerView.setLayoutManager(eLayoutManager);

                recyclerView.setAdapter(leovegasAdapter);
            }

            @Override
            public void onFailure(Call<LeoVegas> call, Throwable t) {

            }
        });




    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem search = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
        search(searchView);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    private void search(SearchView searchView) {

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

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                leovegasAdapter.getFilter().filter(newText);
                return true;
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

更改您的以下代码

少量更改

  • 清除列表
  • 使用addAll填充结果

    public Filter getFilter() {
    
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            //Updated code
            String charString = charSequence.toString();
            ArrayList<Hero> filteredList = new ArrayList<>();
            if (charString.isEmpty()) {
    
                filteredList.addAll(filtarableList);
            } else {
    
                ArrayList<Hero> filteredList = new ArrayList<>();
    
                for (Hero hero : heros) {
    
                    if (hero.getId().toLowerCase().contains(charString) || hero.getName().toLowerCase().contains(charString)) {
    
                        filteredList.add(hero);
                    }
                }
            }
    
            FilterResults filterResults = new FilterResults();
            filterResults.values = filteredList;
            return filterResults;
        }
    
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            //Update code
            heros.clear();
            if (results == null)
                heros.addAll(mFilterConversations);
            else {
                heros.addAll((List<Hero>) results.values);
            }
            notifyDataSetChanged();
    
        }
    };
    }