SearchView en Android con RecyclerView

Muchas aplicaciones representan datos en forma de listas enormes y para filtrar estas listas hemos visto el SearchView presente dentro de estas aplicaciones. Entonces, para filtrar esta lista de datos, generalmente usamos un SearchView. En este artículo, veremos la implementación de Search View en Android con RecyclerView en Android. 

¿Qué vamos a construir en este artículo? 

Construiremos una aplicación simple en la que mostraremos una lista de datos en RecyclerView. Mostraremos la lista de cursos con su descripción y en esa vista de reciclador, agregaremos un SearchView que se utilizará para filtrar los datos en nuestra Vista de reciclador.

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--recycler view to display our data-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVCourses"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
  
</RelativeLayout>

Java

public class CourseModal {
  
    // variables for our course
    // name and description.
    private String courseName;
    private String courseDescription;
  
    // creating constructor for our variables.
    public CourseModal(String courseName, String courseDescription) {
        this.courseName = courseName;
        this.courseDescription = courseDescription;
    }
  
    // creating getter and setter methods.
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getCourseDescription() {
        return courseDescription;
    }
  
    public void setCourseDescription(String courseDescription) {
        this.courseDescription = courseDescription;
    }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:elevation="8dp"
    app:cardCornerRadius="8dp">
  
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
  
        <!--text view for our course name-->
        <TextView
            android:id="@+id/idTVCourseName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="Course Name"
            android:textColor="@color/black"
            android:textSize="18sp" />
  
        <!--text view for our course description-->
        <TextView
            android:id="@+id/idTVCourseDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVCourseName"
            android:padding="5dp"
            android:text="COurse Description"
            android:textColor="@color/black" />
  
    </RelativeLayout>
      
</androidx.cardview.widget.CardView>

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.ViewHolder> {
     
    // creating a variable for array list and context.
    private ArrayList<CourseModal> courseModalArrayList;
    private Context context;
  
    // creating a constructor for our variables.
    public CourseAdapter(ArrayList<CourseModal> courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    // method for filtering our recyclerview items.
    public void filterList(ArrayList<CourseModal> filterllist) {
        // below line is to add our filtered
        // list in our course array list.
        courseModalArrayList = filterllist;
        // below line is to notify our adapter 
        // as change in recycler view data.
        notifyDataSetChanged();
    }
  
    @NonNull
    @Override
    public CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // below line is to inflate our layout.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) {
        // setting data to our views of recycler view.
        CourseModal modal = courseModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseDescTV.setText(modal.getCourseDescription());
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
          
        // creating variables for our views.
        private TextView courseNameTV, courseDescTV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our views with their ids.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
        }
    }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<menu 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
      
    <!--item for our search view with its id-->
    <item
        android:id="@+id/actionSearch"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView" />
      
</menu>

Java

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for
    // our ui components.
    private RecyclerView courseRV;
      
    // variable for our adapter
    // class and array list
    private CourseAdapter adapter;
    private ArrayList<CourseModal> courseModalArrayList;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
          
        // calling method to 
        // build recycler view.
        buildRecyclerView();
    }
  
    // calling on create option menu
    // layout to inflate our menu file.
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // below line is to get our inflater
        MenuInflater inflater = getMenuInflater();
          
        // inside inflater we are inflating our menu file.
        inflater.inflate(R.menu.search_menu, menu);
          
        // below line is to get our menu item.
        MenuItem searchItem = menu.findItem(R.id.actionSearch);
          
        // getting search view of our item.
        SearchView searchView = (SearchView) searchItem.getActionView();
         
        // below line is to call set on query text listener method.
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
  
            @Override
            public boolean onQueryTextChange(String newText) {
                // inside on query text change method we are 
                // calling a method to filter our recycler view.
                filter(newText);
                return false;
            }
        });
        return true;
    }
  
    private void filter(String text) {
        // creating a new array list to filter our data.
        ArrayList<CourseModal> filteredlist = new ArrayList<>();
          
        // running a for loop to compare elements.
        for (CourseModal item : courseModalArrayList) {
            // checking if the entered string matched with any item of our recycler view.
            if (item.getCourseName().toLowerCase().contains(text.toLowerCase())) {
                // if the item is matched we are
                // adding it to our filtered list.
                filteredlist.add(item);
            }
        }
        if (filteredlist.isEmpty()) {
            // if no item is added in filtered list we are 
            // displaying a toast message as no data found.
            Toast.makeText(this, "No Data Found..", Toast.LENGTH_SHORT).show();
        } else {
            // at last we are passing that filtered
            // list to our adapter class.
            adapter.filterList(filteredlist);
        }
    }
  
    private void buildRecyclerView() {
          
        // below line we are creating a new array list
        courseModalArrayList = new ArrayList<>();
          
        // below line is to add data to our array list.
        courseModalArrayList.add(new CourseModal("DSA", "DSA Self Paced Course"));
        courseModalArrayList.add(new CourseModal("JAVA", "JAVA Self Paced Course"));
        courseModalArrayList.add(new CourseModal("C++", "C++ Self Paced Course"));
        courseModalArrayList.add(new CourseModal("Python", "Python Self Paced Course"));
        courseModalArrayList.add(new CourseModal("Fork CPP", "Fork CPP Self Paced Course"));
          
        // initializing our adapter class.
        adapter = new CourseAdapter(courseModalArrayList, MainActivity.this);
          
        // adding layout manager to our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(this);
        courseRV.setHasFixedSize(true);
          
        // setting layout manager 
        // to our recycler view.
        courseRV.setLayoutManager(manager);
          
        // setting adapter to 
        // our recycler view.
        courseRV.setAdapter(adapter);
    }
}

Publicación traducida automáticamente

Artículo escrito por chaitanyamunje y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

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