Implement search functionality with EditText and RecyclerView in android
Search functionality with recyclerview in android.
Here is simple demo to make your recyclerview searchable. By following this demo you can implement search functionality to your RecyclerView in android. Here I got country list and display in Recyclerview.Follow these steps to implement search functionality with RecyclerView :
- Create new project with Android studio.
- Create xml file for MainActivity with RecyclerView and EditText to search.
- Create list to add in RecyclerView.
- Do ready RecyclerView.
- Add “addTextChangedListener” to EditText.
- Override “onTextChanged” with adapter.filter(s);
- Add filter(CharSequence sequence) to your adapter class.
- Now your ready to use your search with RecyclerView.
MainActivity code
private void init() { RecyclerView rvItems = (RecyclerView) findViewById(R.id.rvItems); rvItems.setLayoutManager(new LinearLayoutManager(this)); ArrayList countryList = new ArrayList<>(); for (String s : Locale.getISOCountries()) { countryList.add(new Locale("", s).getDisplayCountry(Locale.ENGLISH)); } final RvSearchDemoAdapter adapter = new RvSearchDemoAdapter(this, countryList); rvItems.setAdapter(adapter); EditText etSearch = (EditText) findViewById(R.id.etSearch); etSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.filter(s); } @Override public void afterTextChanged(Editable s) { } }); }
Adapter class
public class RvSearchDemoAdapter extends RecyclerView.Adapter { private ArrayList countries; private ArrayList countriesCopy; private LayoutInflater inflater; public RvSearchDemoAdapter(Context context, ArrayList countries) { this.countries = countries; this.countriesCopy = new ArrayList<>(); countriesCopy.addAll(countries); inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public RvSearchDemoHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new RvSearchDemoHolder(inflater.inflate(R.layout.item_country, parent, false)); } @Override public void onBindViewHolder(RvSearchDemoHolder holder, int position) { holder.bind(countries.get(position)); } @Override public int getItemCount() { return countries.size(); } public void filter(CharSequence sequence) { ArrayList temp = new ArrayList<>(); if (!TextUtils.isEmpty(sequence)) { for (String s : countries) { if (s.toLowerCase().contains(sequence)) { temp.add(s); } } } else { temp.addAll(countriesCopy); } countries.clear(); countries.addAll(temp); notifyDataSetChanged(); temp.clear(); } }
Get detailed project from Github,
Share this content: