Android ActionBar SearchView Autocomplete Example

This example will show you how to use android.support.v7.widget.SearchView class to add a search box and implement autocomplete function for the search box. It also demos how to use android.support.v7.widget.ShareActionProvider to open the share application list for your android application.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/wUclFlElP6U

1. ActionBar Menu Xml File.

  1. There are two menus in this action bar. One is a SearchView another is a ShareActionProvider.
  2. The menu XML file is saved in the app/res/menu folder, it’s name is action_bar_search_example_menu.xml.
  3. Below is the source code of the action_bar_search_example_menu.xml file.
    <?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/app_bar_menu_search"
            android:icon="@drawable/icon_search_32"
            android:title="Search"
            app:actionViewClass="android.support.v7.widget.SearchView"
            app:showAsAction="ifRoom|collapseActionView" />
    
        <item
            android:id="@+id/app_bar_menu_share"
            android:title="Share"
            app:showAsAction="never"
            app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>
    </menu>

2. Activity Java File.

  1. ActionBarSearchActivity.java
    package com.dev2qa.example;
    
    import android.content.Intent;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.SearchView;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Toast;
    import android.support.v7.widget.ShareActionProvider;
    
    public class ActionBarSearchActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_action_bar_search);
    
            // Get ActionBar
            ActionBar actionBar = getSupportActionBar();
            // Set below attributes to add logo in ActionBar.
            actionBar.setDisplayShowHomeEnabled(true);
            actionBar.setDisplayUseLogoEnabled(true);
            actionBar.setLogo(R.drawable.icon_tech_32);
    
            actionBar.setTitle("dev2qa.com - Search Example");
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
    
            // Inflate the search menu action bar.
            MenuInflater menuInflater = getMenuInflater();
            menuInflater.inflate(R.menu.action_bar_search_example_menu, menu);
    
            // Get the search menu.
            MenuItem searchMenu = menu.findItem(R.id.app_bar_menu_search);
    
            // Get SearchView object.
            SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenu);
    
            // Get SearchView autocomplete object.
            final SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
            searchAutoComplete.setBackgroundColor(Color.BLUE);
            searchAutoComplete.setTextColor(Color.GREEN);
            searchAutoComplete.setDropDownBackgroundResource(android.R.color.holo_blue_light);
    
            // Create a new ArrayAdapter and add data to search auto complete object.
            String dataArr[] = {"Apple" , "Amazon" , "Amd", "Microsoft", "Microwave", "MicroNews", "Intel", "Intelligence"};
            ArrayAdapter<String> newsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, dataArr);
            searchAutoComplete.setAdapter(newsAdapter);
    
            // Listen to search view item on click event.
            searchAutoComplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int itemIndex, long id) {
                    String queryString=(String)adapterView.getItemAtPosition(itemIndex);
                    searchAutoComplete.setText("" + queryString);
                    Toast.makeText(ActionBarSearchActivity.this, "you clicked " + queryString, Toast.LENGTH_LONG).show();
                }
            });
    
            // Below event is triggered when submit search query.
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    AlertDialog alertDialog = new AlertDialog.Builder(ActionBarSearchActivity.this).create();
                    alertDialog.setMessage("Search keyword is " + query);
                    alertDialog.show();
                    return false;
                }
    
                @Override
                public boolean onQueryTextChange(String newText) {
                    return false;
                }
            });
    
    
            // Get the share menu item.
            MenuItem shareMenuItem = menu.findItem(R.id.app_bar_menu_share);
            // Because it's actionProviderClass is ShareActionProvider, so after below settings
            // when click this menu item A sharable applications list will popup.
            // User can choose one application to share.
            ShareActionProvider shareActionProvider = (ShareActionProvider)MenuItemCompat.getActionProvider(shareMenuItem);
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/*");
            shareActionProvider.setShareIntent(shareIntent);
    
            return super.onCreateOptionsMenu(menu);
        }
    }

3. Main Layout Xml File.

  1. activity_action_bar_search.xml: This XML is too simple, there is no view object in it.

4. Icon Image Files.

You need to add the below icon images in the app/res/drawable folder.

  1. icon_tech_32
  2. icon_search_32
3.5 2 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Ameer
Ameer

Thanks a lot, you saved my life 🙂

Badwa
Badwa
Reply to  Ameer

Mine too.

Kotliner
Kotliner

Can someone help me, please? I’m trying to convert this in kotlin, and the only error i am getting is an error in :-
searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text) as SearchView.searchAutoComplete

“searchAutoComplete” is in red. I don’t know why. It says unresolved reference. Please help.

Sunil Khandekar
Sunil Khandekar

Thanks

4
0
Would love your thoughts, please comment.x
()
x