Skip to content
Related Articles

Related Articles

Android SearchView with Example
  • Difficulty Level : Hard
  • Last Updated : 18 Feb, 2021

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




    <?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>

  • 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




    <?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>  

  • 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




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

Output:

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

  • Search results

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :