Android SearchView Action Bar Tutorial

Last modified on March 26th, 2015 by Joe.

This Android tutorial is to learn about using a SearchView in action bar of an Android app. There are two main things that I will handle in this tutorial. Incorporating a Search component in the Android action bar is a common use which we come quite often. This example Android application accompanying this tutorial can be used as a base wireframe to get your searchview done.

We will focus on two main things in this tutorial. First one is using AppCompat-v7 library for support and the second one is customizing the ActionBar is with a custom theme. These two items gives a feeling that it is going to be simple and straight forward. There are couple of configurations we need to get right or else we will be losing many hours on this. I have got some fuming to do and let me reserve it for the conclusion.

Android-SearchView-Action-Bar

Gradle Dependencies for AppCompat-v7

To use the appcompat-v7 support library, we should add the library in Gradle dependency. This is for people using Android Studio. For people using Eclipse+ADT, I recommend you to migrate to Android Studio as soon as possible. Since with my personal experience for Android development, Android Studio is way better than Eclipse. See the API support range, 11 to 21.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.javapapers.android.androidsearchviewactionbar"
        minSdkVersion 11
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

Android Manifest for SearchView Example

  1. You have to notice the theme applied for the activity(s). It is important to get the AppCompat right.
  2. meta-data on the MainActivity points to the Search results activity.
  3. intent-filter in SearchResultsActivity to identify this as searchable activity.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javapapers.android.androidsearchviewactionbar" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.MyCompatTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="android.app.default_searchable"
                android:value=".SearchResultsActivity" />
        </activity>

        <activity
            android:name=".SearchResultsActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.MyCompatTheme">

            <!-- to identify this activity as "searchable" -->
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>
    </application>
</manifest>

Android SearchView in Menu

Put the following menu_main.xml in menu folder. We have included an item with actionViewClass as SearchView. This is from appcompat-v7 support library.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:appcompat="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/tools">

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never"/>

    <item
        android:id="@+id/menu_search"
        android:title="@string/menu_search"
        appcompat:actionViewClass="android.support.v7.widget.SearchView"
        appcompat:showAsAction="always"/>

</menu>

Styling Search View in Android Action Bar

Let us change the background color of the action bar. You can use this as a base template and add more customizations to the search view elements.

<resources>
    <style name="AppBaseTheme" parent="android:Theme.Light">
    </style>

    <style name="AppTheme" parent="AppBaseTheme">
    </style>

    <style name="Theme.MyCompatTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:windowBackground">@color/winBackground</item>
        <item name="android:actionBarStyle">@style/ActionBar</item>
        <item name="actionBarStyle">@style/ActionBar</item>
    </style>

    <style name="ActionBar"
        parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@color/background</item>
        <item name="background">@color/background</item>
    </style>

    <color name="winBackground">#98cb4a</color>
    <color name="background">#f76d3c</color>
</resources>

Searchable SearchView

Add the following searchable.xml file in folder “res/xml”.

<?xml version="1.0" encoding="utf-8"?>

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint" />

Search View Main Activity

MainActivity.java, in this class look at the way the SearchView component is inflated in onCreateOptionsMenu

package com.javapapers.android.androidsearchviewactionbar;

import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        // Inflate menu to add items to action bar if it is present.
        inflater.inflate(R.menu.menu_main, menu);
        // Associate searchable configuration with the SearchView
        SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.menu_search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));

        return true;
    }
}

MainActivity Layout – activity_mail.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

</RelativeLayout>

Search Results Activity

SearchResultsActivity.java, in this class look at the way onNewIntent(Intent) method is overriden and handled. This is where we will get the search input query and our search against the data bank.

package com.javapapers.android.androidsearchviewactionbar;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;

public class SearchResultsActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        handleIntent(getIntent());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.menu_search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));

        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {

        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            //use the query to search
        }
    }
}

activity_result.xml, the layout for search results.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="#ff3dc0ff">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/search_result" />

</RelativeLayout>

SearchView-Action-Bar-Search-Input

SearchView-Action-Bar-Customization

Search-Result

Download the SearchView Example Android Application

Download

Conclusion – A Plea to Android Platform Team

This Android tutorial is result of the difficulties I faced in getting the appcompat-v7 library work nicely with Android action bar and the couple of hours lost on customizing the Android action bar. The main issue I faced now and a prolonged one is the outdated Android documentation. In many areas, the Android official documentation is lagging behind. In some places there are outdated example applications with deprecated API usage. This is really a pain for an average Android developer. Smart  people can always refer the source and find their way forward. But for a beginner and a normal developer, we need good documentation. Third party tutorials and blogs are mostly outdated and using very old API version.

One more area to be improved is the Javadoc comments for the APIs. In most of the places, there are one line comments. In Java JDK, the Javadoc for APIs are excellent. Whenever there is a method supposed to be used in complex use cases, it comes with detailed explanation, sometimes with example code. If the same kind of Javadoc documentation can be emulated for Android, then it will really help. Why all this fuming now is, Android API versions are getting churned out at a break neck speed. APIs are getting complex to use as the versions increase and it is understandable that backwards compatibility has to be maintained. We do thank for the speed at which feature are being added to Android platform. At the same time, we request you, please update the documentation before the API release and add as much as Javadoc comments possible in the code. Thanks.

Comments on "Android SearchView Action Bar Tutorial"

  1. Firoz Shaikh says:

    Yes Joe You are right in your Last Paragraph.
    .
    By The way thanks, Today only i have to perform Search Facility task and today only i check my mail, your tutorial was there.
    Thank you so much Gem.

  2. munawar says:

    sir i dont no how to writethe java code could u explain me

  3. Matias says:

    Hi, doesn ´t work if i make toast in the handleIntent function, nothing appair

  4. Mohab says:

    thanks joe for this useful tutorial .
    i have a question
    i want open search activity if search icon clicked not when it click enter or go in keyboard.
    how can i do that ?
    thanx in advance .

  5. Madasamy says:

    Thanks Joe. It very useful for me.
    But when i perform search, SearchResultsActivity#handleIntent(intent) call two times.

  6. Will says:

    My app keeps on force closing after using this method, any help would be appreciated.

  7. erum says:

    how to achive this actionbar with searchview … i have tried using custom xml layout for actionbar i have set as wel but im not gettig perfect answer …..

  8. pico says:

    Ur right in the last paragraph except one thing. All the peopel need good docs, smart as well as avg dev. No one wants to reverse engineer an API and looking at the source. That defies the purpose of APIs.

  9. ankit says:

    Hi Joe, thanks for this tutorial, it is very useful…
    Please make changes in MainActivity by replacing
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    with
    ComponentName cn = new ComponentName(this, SearchResultsActivity.class);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(cn);
    because MainActivity is not the searchable activity..

  10. Ajijulla says:

    hi frd i don’t were to apply the plugin code pls to tell were to apply the plugin i got some error in that code am waiting for your reply

Comments are closed for "Android SearchView Action Bar Tutorial".