Articles → Android → Search functionality using searchview in android

Search functionality using searchview in android






What is SearchView?





Example






<?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    
                  xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    
                  android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".debug.Demo">    
                  
                  <ListView        android:id="@+id/lView"        
                              android:layout_width="match_parent"        
                              android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>









Click to Enlarge




Click to Enlarge




Click to Enlarge








Click to Enlarge




Click to Enlarge



<?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">
        <item android:id="@+id/search" android:title="Search"    app:showAsAction="always"    
        app:actionViewClass="android.widget.SearchView" />
</menu>




String fruitlist[] = {"apple","banana","orange","cherry"};
ListView listView = (ListView) findViewById(R.id.lView);
adapter =  new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, fruitlist);
listView.setAdapter(adapter);




@Override
public boolean onCreateOptionsMenu(Menu menu)
{    
    MenuInflater inflater = getMenuInflater();    
    inflater.inflate(R.menu.search_option, menu);    
    MenuItem item = menu.findItem(R.id.search);    
    
    SearchView searchView = (SearchView)item.getActionView();    
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() 
    {        
          @Override        
          public boolean onQueryTextSubmit(String s) 
          {            
              return false;        
          }        
          
          @Override        
          public boolean onQueryTextChange(String s) 
          {            
              adapter.getFilter().filter(s);            
              return false;        
          }    
    });    return true;}



Output





Click to Enlarge




Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, November 19, 2019

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250