Android SearchView with Example

Search View widget is used to provide a search interface to user so that the user can enter his search query and submit a request to search provider and get a list of query suggestions or results.

Class Syntax:

public class SearchView
extends LinearLayout
implements CollapsibleActionView

Class Hierarchy:



java.lang.Object
  ↳  android.view.View
    ↳  android.view.ViewGroup
      ↳  android.widget.LinearLayout
        ↳  android.widget.SearchView

Example to demonstrate SearchView:
In this article you will create a basic search application with search view and list view. User will type search query in search view which is present in action bar. Here are explained steps:

  • Step 1: activity_main.xml

    It consist of Relative Layout with ListView in it from which data is to be search. Here is complete code for activity_main.xml:

    activity_main.xml

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?xml version="1.0" encoding="utf-8"?>
    <!--Relative Layout-->
      
    <RelativeLayout 
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/relativelayout">
      
        <!--List View from which data is to be searched-->
        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            />
      
    </RelativeLayout>

    chevron_right

    
    

  • Step 2: menu.xml

    Create menu.xml and add search view as menu item to Action Bar with title as “Search” this file. Here is complete code for menu.xml file.

    menu.xml

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?xml version="1.0" encoding="utf-8"?>  
      
    <menu 
        xmlns:android="http://schemas.android.com/apk/res/android">   
      
        <!--Search view widget as item in menu-->
        <item  
            android:id="@+id/search_bar"  
            android:title="Search" 
            app:actionViewClass="android.widget.SearchView" 
            app:showAsAction="ifRoom|withText"  
        />  
    </menu>  

    chevron_right

    
    

  • Step 3:MainActivity.java
    Next step is to set up the code for main activity. In this java file items are added to List View manually and setOnQueryTextListener is attached to Search View. onQueryTextSubmit() method is overriden in which List View get filter according to the search query entered by the user.Here is complete code for MainActivity.java:

    MainActivity.java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    package com.geeksforgeeks.searchviewwidget;
      
    import android.support.v7.app.AppCompatActivity;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.os.Bundle;
    import android.widget.ListView;
    import android.widget.ArrayAdapter;
    import android.widget.SearchView;
    import java.util.ArrayList;
      
    public class MainActivity extends AppCompatActivity {
      
        // List View object
        ListView listView;
      
        // Define array adapter for ListView
        ArrayAdapter<String> adapter;
      
        // Define array List for List View data
        ArrayList<String> mylist;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
            // initialise ListView with id
            listView = findViewById(R.id.listView);
      
            // Add items to Array List
            mylist = new ArrayList<>();
            mylist.add("C");
            mylist.add("C++");
            mylist.add("C#");
            mylist.add("Java");
            mylist.add("Advanced java");
            mylist.add("Interview prep with c++");
            mylist.add("Interview prep with java");
            mylist.add("data structures with c");
            mylist.add("data structures with java");
      
            // Set adapter to ListView
            adapter
                = new ArrayAdapter<String>(
                    this,
                    android.R.layout.simple_list_item_1,
                    mylist);
            listView.setAdapter(adapter);
        }
      
        @Override
        public boolean onCreateOptionsMenu(Menu menu)
        {
            // Inflate menu with items using MenuInflator
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu, menu);
      
            // Initialise menu item search bar
            // with id and take its object
            MenuItem searchViewItem
                = menu.findItem(R.id.search_bar);
            SearchView searchView
                = MenuItemCompat
                      .getActionView(searchViewItem);
      
            // attach setOnQueryTextListener
            // to search view defined above
            searchView.setOnQueryTextListener(
                new SearchView.OnQueryTextListener() {
      
                    // Override onQueryTextSubmit method
                    // which is call
                    // when submitquery is searched
      
                    @Override
                    public boolean onQueryTextSubmit(String query)
                    {
                        // If the list contains the search query
                        // than filter the adapter
                        // using the filter method
                        // with the query as its argument
                        if (list.contains(query)) {
                            adapter.getFilter().filter(query);
                        }
                        else {
                            // Search query not found in List View
                            Toast
                                .makeText(MainActivity.this,
                                          "Not found",
                                          Toast.LENGTH_LONG)
                                .show();
                        }
                        return false;
                    }
      
                    // This method is overridden to filter
                    // the adapter according to a search query
                    // when the user is typing search
                    @Override
                    public boolean onQueryTextChange(String newText)
                    {
                        adapter.getFilter().filter(newText);
                        return false;
                    }
                });
      
            return super.onCreateOptionsMenu(menu);
        }
    }

    chevron_right

    
    

Output:

  • Main Activity with search bar and list
  • Search results according to search query

  • Search results


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.