Saltar al contenido

Android: implementación de un filtro de búsqueda en un RecyclerView

Te damos la bienvenida a nuestra página web, en este lugar vas a hallar la solucíon a lo que buscabas.

Solución:

en su adaptador agregue una nueva función para actualizar la lista

public void updateList(List list)
     displayedList = list;
     notifyDataSetChanged();

agregar textWatcher para la búsqueda permite decir que está usando Edittext como campo de búsqueda

searchField.addTextChangedListener(new TextWatcher() 
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) 

            // TODO Auto-generated method stub
        

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) 

            // TODO Auto-generated method stub
        

        @Override
        public void afterTextChanged(Editable s) 

            // filter your list from your input
            filter(s.toString());
            //you can use runnable postDelayed like 500 ms to delay search text
        
    );

Función de filtro simple

void filter(String text)
     List temp = new ArrayList();
     for(DataHolder d: displayedList)
           //or use .equal(text) with you want equal match
           //use .toLowerCase() for better matches
           if(d.getEnglish().contains(text))
               temp.add(d);
           
     
     //update recyclerview
     disp_adapter.updateList(temp);

Con Cuchillo de mantequilla

@OnTextChanged(R.id.feature_manager_search)
protected void onTextChanged(CharSequence text) 
    filter(text.toString());

he hecho así

Archivo .XMl






    








Archivo de clase .JAVA

package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONObject;

import java.util.ArrayList;

public class Home extends AppCompatActivity implements ResultCallBack

SQLiteDatabase db;

ArrayList alCategorName=new ArrayList<>();

RecyclerView rvCategory;
EditText etSearch;
Category bookadapter;
ArrayList alBookInfo;

String strURL="http://localhost:21246/api/TreasuryBooks?BookId=1";

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitleTextColor(getResources().getColor(R.color.white));
    setSupportActionBar(toolbar);

//        AsyncTask_WebAPI asyncTask=new AsyncTask_WebAPI(this,strURL,this);
//        asyncTask.execute();

    etSearch=(EditText)findViewById(R.id.etSearch);
    etSearch.setText("");

    DatabaseAccess da= DatabaseAccess.getInstance(this);
    db=da.open();
    alBookInfo=new ArrayList();

    Cursor c = db.rawQuery("select BookName from Books", null);
    int rows = c.getCount();

    c.moveToFirst();

    for(int i=0;i

Adaptador Recyclerview

  //Recycler view adapter Class with filterable interface

   private class Category extends RecyclerView.Adapter implements Filterable

    ArrayList alBooks=new ArrayList();
    Context context;
    viewHolder holder;

    public  Category()
    

    public Category(Context context,ArrayList albooks)
    
        this.context=context;
        this.alBooks=albooks;
    

    @Override
    public int getItemCount() 
        return alBooks.size();
    

    @Override
    public viewHolder onCreateViewHolder(ViewGroup parent, int viewType) 

        View v=    LayoutInflater.from(parent.getContext()).inflate(R.layout.home_cardview,parent,false);
        holder=new viewHolder(v);
        return holder;
    

    @Override
    public void onBindViewHolder(viewHolder holder, int position) 
        holder.tvBookName.setText(alBooks.get(position));
    

    private Filter fRecords;

   //return the filter class object
    @Override
    public Filter getFilter() 
        if(fRecords == null) 
            fRecords=new RecordFilter();
        
        return fRecords;
    

   //filter class
    private class RecordFilter extends Filter 

        @Override
        protected FilterResults performFiltering(CharSequence constraint) 

            FilterResults results = new FilterResults();

            //Implement filter logic
    // if edittext is null return the actual list
            if (constraint == null 

        @Override
        protected void publishResults(CharSequence constraint,FilterResults results) 

       //it set the data from filter to adapter list and refresh the recyclerview adapter
            alBooks = (ArrayList) results.values;
            notifyDataSetChanged();
           
       
   

   private class viewHolder extends  RecyclerView.ViewHolder 
    CardView cv;
    TextView tvBookName;

    viewHolder(final View itemview) 
        super(itemview);

        cv = (CardView) itemview.findViewById(R.id.cardview);
        tvBookName = (TextView) itemview.findViewById(R.id.categoryName);

        itemview.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Intent intent=new       Intent(Home.this,Act_Fragment_Container.class);
                intent.putExtra("BookName", tvBookName.getText());
                startActivity(intent);
            
        );
    
   

agregue el adaptador de vista del reciclador en la misma clase para evitar confusiones ...

Implementar SearchView.OnQueryTextListener

public class Countries_List extends AppCompatActivity  implements SearchView.OnQueryTextListener 

    //your Model Class

    List dataList, filteredDataList;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem item=menu.findItem(R.id.action_search);
        SearchView searchView=(SearchView)MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(this);

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

    @Override
    public boolean onQueryTextChange(String newText) 

        filteredDataList = filter(dataList, newText);
        mAdapter.setFilter(filteredDataList);
        return true;
    
    public boolean onOptionsItemSelected(MenuItem item) 
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_search) 
            return true;
        

        return super.onOptionsItemSelected(item);
    
    private List filter(List dataList, String newText) 
        newText=newText.toLowerCase();
        String text;
        filteredDataList=new ArrayList<>();
        for(Countries dataFromDataList:dataList)
            text=dataFromDataList.getTitle().toLowerCase();

            if(text.contains(newText))
                filteredDataList.add(dataFromDataList);
            
        

        return filteredDataList;
    

Y, en su clase de adaptador:

void setFilter(List FilteredDataList) 
        countriesList = FilteredDataList;
        notifyDataSetChanged();
    

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *