📜  带有RecyclerView的Android中的SearchView

📅  最后修改于: 2021-05-13 18:19:32             🧑  作者: Mango

许多应用程序都以巨大列表的形式表示数据,并且为了过滤这些列表,我们已经看到这些应用程序中存在SearchView。因此,为了过滤此数据列表,我们通常使用SearchView。在本文中,我们将研究Android中的Search View与Android中的RecyclerView的实现。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在其中将在RecyclerView中显示数据列表。我们将显示带有其描述的课程列表,并在该“回收者”视图上,添加一个SearchView,该过滤器将用于过滤“回收者”视图中的数据。下面提供了一个示例视频,以使您对本文中的工作有个大概的了解。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML


  
    
    
  


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


  
    
  
        
        
  
        
        
  
    
      


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 {
     
    // creating a variable for array list and context.
    private ArrayList courseModalArrayList;
    private Context context;
  
    // creating a constructor for our variables.
    public CourseAdapter(ArrayList courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    // method for filtering our recyclerview items.
    public void filterList(ArrayList 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


      
    
    
      


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 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 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);
    }
}


第3步:创建用于存储数据的模式类

导航到应用程序> Java >您的应用程序的程序包名称>右键单击它>新建> Java类,并将您的类命名为CourseModal,然后将以下代码添加到其中。

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;
    }
}

步骤4:为我们的RecyclerView项目创建一个布局文件

导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将您的布局命名为course_rv_item ,并将以下代码添加到其中。

XML格式



  
    
  
        
        
  
        
        
  
    
      

第5步:创建一个适配器类以将数据设置为我们RecyclerView的项目

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为CourseAdapter,然后将以下代码添加到其中。

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 {
     
    // creating a variable for array list and context.
    private ArrayList courseModalArrayList;
    private Context context;
  
    // creating a constructor for our variables.
    public CourseAdapter(ArrayList courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    // method for filtering our recyclerview items.
    public void filterList(ArrayList 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);
        }
    }
}

步骤6:为SearchView创建菜单文件

导航到应用程序> res>右键单击它> New> Directory并为您的目录命名,作为菜单。创建新目录后,我们必须在其中创建一个新菜单文件。用于创建新的菜单文件。导航到应用程序> res>菜单>右键单击它> New>菜单资源文件,将其命名为search_menu并添加以下代码。

XML格式



      
    
    
      

步骤7:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

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 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 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);
    }
}

现在运行您的应用程序,并查看该应用程序的输出。

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!