Android SearchView Tutorial in Android Studio

Android SearchView Tutorial in Android Studio

SearchView in Android is a very sought after View. You cannot find any website nowadays, without a search bar. The same applies to an application also. There are a lot of ways to auto-populate a search query on entering a key phrase into the SearchView. In this tutorial, we will see a detailed tutorial with an example of creating a ListView to serve the answers for our Search.

Android SearchView Basics

You can define a SearchView in Android XML using the <SearchView> Tag or SearchView Class in your Activity. An XML implementation of the SearchView is given below.

YOU ARE YOUR BOSS
I agree to have my personal information transfered to MailChimp ( more information )
Join over 5.000 visitors who are receiving our free content and learn how to program with Android. The growth of Android is estimated to reach a whooping 83% by 2020. Hop on the train and start making money!
We hate spam. Your email address will not be sold or shared with anyone else.
<SearchView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/search_view">

</SearchView>

This creates a Search View with a Search Icon like below.

SearchView ICON
SearchView ICON

A Search View takes in a lot of other attributes to it. See below for the list of all the available attributes.

SearchView – XML Attributes

The list of all the attributes unique to SearchView is given below.

  • android:queryHint
    This attribute takes in a Text/String as its value. It lets you set an optional query hint string to be displayed in the empty query field. This means that, instead of a simple icon being present, it lets you show a hint or text for the user to understand. Find the below example to illustrate the same.

    <SearchView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/search_view"
        android:queryHint="Search here">

SearchView QueryHint

 

android:queryBackground –
This lets you set a Background Color to the Query Hint that you specified above. See the below example.

<SearchView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/search_view"
    android:queryHint="Search here"
    android:queryBackground="@android:color/holo_purple">

SearchView QueryBackground

  • android:iconifiedByDefault –
    This is the default state of the Search View. If it is true, it will show an icon and expand when clicked. If it is false, it will be in an expanded position all the time. See the example below.
<SearchView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/search_view"
    android:queryHint="Search here"
    android:iconifiedByDefault="false">
iconifiedByDefault
Notice how the X Mark is not present when the iconifiedByDefault is set to false
  • android:inputType – 
    This lets you choose what type of input is going to be entered into the Search View. This is very useful if you want to restrict the search query to one particular type. See the example below,

    <SearchView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/search_view"
        android:queryHint="Search here"
        android:inputType="number">

    "<yoastmark

     

  • android:maxWidth –
    This specifies the maximum width of the SearchView. This is an optional parameter and can be specified if there are going to be dynamic views created. To protect the Integrity of the UI it is advised to specify the max width to which the Search View can scale to. See the example code below,

    <SearchView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/search_view"
        android:queryHint="Search here"
        android:inputType="number"
        android:maxWidth="25sp">

SearchView Methods in Android

This section consists of all the important Method calls required by the SearchView. You will probably be using some in the example program given below.

  • getInputType() – 
    This method helps you to return the input type that the query text field holds. You can use this method on the object of a SearchView Class like below.

    SearchView searchView = findViewById(R.id.search_view);
    Integer inputType = searchView.getInputType();
  • setInputType() – 
    This method is a setter to make the query text field to be of a certain type. There are various types that you can give, Date, Time, Text, Number etc.

    SearchView searchView = findViewById(R.id.search_view);
    searchView.setInputType(InputType.TYPE_CLASS_TEXT);

    Make use of the InputType class to set the Constant to the setInputType method. There are a lot of constants that are available for Day, Date, Time, Number, Text etc.

  • getQuery() – 
    This method is used to retrieve the text query that the user has input on the query field. You will be using this to make a search in your database and setting the result back. See the example call below

    SearchView searchView = findViewById(R.id.search_view);
    CharSequence query = searchView.getQuery();
  • setQuery(CharSequence, Boolean) – 
    This is a setter method, which will help us to set the query ourselves. This may not be used very often since the user is responsible for entering the query most of the time. It takes an additional parameter, which is a boolean variable which denotes if the query should be submitted or just entered and wait for the user to submit. An example call is given below,

    SearchView searchView = findViewById(R.id.search_view);
    CharSequence query = "Sample";
    searchView.setQuery(query,true);
  • getQueryHint() – 
    This is a getter to retrieve the query hint we specified in our XML layout. See the example usage below,

    SearchView searchView = findViewById(R.id.search_view);
    CharSequence query = searchView.getQueryHint();
  • setQueryHint() – 
    This is a setter method to specify which query hint is to be given to the Search View. You can see the example implementation below,

    SearchView searchView = findViewById(R.id.search_view);
    CharSequence query = "Sample";
    searchView.setQueryHint(query);
  • isIconfiedByDefault() – 
    This method returns a boolean value informing if the Search View class is iconified (Shows icon in idle state and expands into a search view when clicked) or not. The example implementation is given below,

    SearchView searchView = findViewById(R.id.search_view);
    Boolean isIconfied = searchView.isIconfiedByDefault();
  • setIconifiedByDefault(Boolean) – 
    This method is used to set if the Search View should be iconified or not. By default it is true, so you can make use of this method to set it to false. Example Implementation is,

    SearchView searchView = findViewById(R.id.search_view);
    searchView.setIconifiedByDefault(false);
  • setOnQueryTextFocusChangeListener(View.OnFocusChangeListenerlistener) – 
    This is a listener that will wait for the user to click on the focus area. The onFocusChange callback is fired as soon as the user does that, and we can specify our actions inside that. You can change or manipulate a data value present inside that as needed. Example skelton code for the listener is given below,

    SearchView searchView = findViewById(R.id.search_view);
    searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener(){
    
        @Override
        public void onFocusChange(View view, boolean b) {
        // Do your magic here
        }
        
    });
  • setOnQueryTextListener(SearchView.OnQueryTextListenerlistener) – 
    This listener is helpful when you have to record user actions on the query field. It retrieves the text on the query field in the onQueryTextChange callback and the onQueryTextSubmit callback gets the final query that the user submits. Note that we are using the SearchView.OnQueryTextListener and not View.OnQueryTextListener. This is because the SearchView class holds the OnQueryTextListener and it is specific to that only. See the example skeleton code below,

    SearchView searchView = findViewById(R.id.search_view);
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
    
        @Override
        public boolean onQueryTextSubmit(String s) {
            return false;
        }
    
        @Override
        public boolean onQueryTextChange(String s) {
            return false;
        }
    });
  • setOnSuggestionListener(SearchView.OnSuggestionListener) – 
    This listener fires whenever the user clicks or selects the Suggestions that are going to populate on the SearchView bar. You can make sure to perform some action on clicking it( Like opening a new activity or changing the data field etc). An example skeleton code is given below.

    SearchView searchView = findViewById(R.id.search_view);
    searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener(){
    
        @Override
        public boolean onSuggestionSelect(int i) {
            return false;
        }
    
        @Override
        public boolean onSuggestionClick(int i) {
            return false;
        }
    })

 

SearchView example using ListView in Android Studio

The Goal of this Example is to Create a ListView and populate the search results in that list view. We will achieve this by making use of our custom Adapter. 

STEP 1

Create a Sample Android Project using Android Studio. Now create an XML name search_view.xml and an Activity name MainActivity.java.

STEP 2

Open the search_view.xml and create a sample layout file like below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <SearchView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/search_view"
        android:queryHint="Search here"
        android:inputType="text">

    </SearchView>
    <ListView
        android:id="@+id/list_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
     />
</LinearLayout>
STEP 3

Open the MainActivity.java class and instantiate it as an Activity (extend Activity and override the OnCreate()). Once done, you can create the following code.

package com.monks.android.newapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    // Declare Variables
    ListView list;
    AdapterClass adapter;
    SearchView editsearch;
    String[] searchQueries;
    ArrayList<SearchQuery> arraylist = new ArrayList<SearchQuery>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_view);
        searchQueries = new String[]{"TextView", "ListView", "SearchView",
                "RatingBar", "ToolBar", "Button", "EditText", "ToggleButton",
                "ImageView","SlidingDrawer","Android"};

        list = (ListView) findViewById(R.id.list_view);
        for (String searchQuery:searchQueries) {
            SearchQuery searchQuery1 = new SearchQuery(searchQuery);
            // Binds all strings into an array
            arraylist.add(searchQuery1);
        }
        adapter = new AdapterClass(this, arraylist);
        list.setAdapter(adapter);
        editsearch = (SearchView) findViewById(R.id.search_view);
        editsearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                String text = newText;
                adapter.filter(text);
                return false;
            }
        });
    }
}
STEP 4

Before we jump into anything more, we will be required to create a simple Modal that will be the placeholder for our SearchQuery. We will name it SearchQuery.java as such. See the implementation of the Modal below.

package com.monks.android.newapplication;

public class SearchQuery {

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    private String query;
public SearchQuery(String query)
{
    this.query = query;
}
}
Step 5

Before our Final Adapter, we will also be in need of a layout file that will come inside the ListView layout file. We can create a simple layout holding a TextView. See the list_items.xml layout file below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        />
</RelativeLayout>
STEP 6

Now, it is time to create the AdapterClass to help in loading our ListView with the data required. Also, note that additionally, we are performing filter() operation inside the AdapterClass. This will help in creating a filtered output back to our ListView. See the implementation below

package com.monks.android.newapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class AdapterClass extends BaseAdapter {


    Context mContext;
    LayoutInflater inflater;
    private List<SearchQuery> searchQueries = null;
    private ArrayList<SearchQuery> arraylist;

    public AdapterClass(Context context, List<SearchQuery> searchQueries) {
        mContext = context;
        this.searchQueries = searchQueries;
        inflater = LayoutInflater.from(mContext);
        this.arraylist = new ArrayList<SearchQuery>();
        this.arraylist.addAll(searchQueries);
    }

    public class ViewHolder {
        TextView name;
    }

    @Override
    public int getCount() {
        return searchQueries.size();
    }

    @Override
    public SearchQuery getItem(int position) {
        return searchQueries.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.list_items, null);
            // Locate the TextViews in listview_item.xml
            holder.name = (TextView) view.findViewById(R.id.name);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Set the results into TextViews
        holder.name.setText(searchQueries.get(position).getQuery());
        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        searchQueries.clear();
        if (charText.length() == 0) {
            searchQueries.addAll(arraylist);
        } else {
            for (SearchQuery wp : arraylist) {
                if (wp.getQuery().toLowerCase(Locale.getDefault()).contains(charText)) {
                    searchQueries.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }

}
STEP 7

Time to run the application and see what the SearchView does in Android.

 

Also Read  ImageView in Android - Overview and Implementation

Leave a Comment

Your email address will not be published. Required fields are marked *