How to implement SearchView in ActionBar in Android

In android it is always preferred to implement the searchview in action bar. Because if we implement the searchview in the actionbar it will be convenient for the user regardless of the scrolling or other activities taking place inside the screen. In this tutorial we will implement an example project of for implementing searchview in actionbar.

We can implement a searchview in actionbar by placing the search widget inside the menu file of activity. It will allow to show just a search icon as other menu items and it will expand and collapse by hiding all other widgets in the actionbar when the user clicks on the search icon.

Note :This is an example of a searchable listview which contains list of programming languages

Steps

  1. Create new project in android studio
  2. Create xml folder and implement searchable file
  3. Configure AndroidManifest.xml with necessary tags
  4. Place the searchview widget in your activity’s menu file
  5. Add the listview in your layout file (listview which search to be implemented.
  6. Implement the java code for searching.

Create project in android studio

Refer Android beginners app development guide if you are beginner or if you don’t know how to create project in android studio.

Create xml folder and implement searchable file

For implementing a search in actionbar you need to have an xml folder containing the searchable file. For doing that  create an xml folder under res and inside xml directory create a file and name it as Searchable

Here is the code for Searchable.xml

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

Configure the AndroidManifest.xml with necessary tags

Now we need to have some tags in our AndroidManifetst.xml file . Add the following tags inside the activity tags which you are using the search task. This is important for implementing search in particular activity.

<intent-filter> 
   <action android:name="android.intent.action.SEARCH" />
</intent-filter>

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

Place the searchview widget in your menu file

Since we need to display search icon in action bar we need to have the widget in menu file of activity which will display icons on actionbar .So you need to have the searchview to your res/menu/menu_main.xml file

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="codes4.com.simplelistview.MainActivity">

    <item
        android:id="@+id/mi_search"
        android:title="search something"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"
        />

</menu>

Now we will start implementing listview

Note: Here the search is processing in listview, so it is important to have idea regarding implementing listview in android. Refer Android listview example if you are not familiar with implementing listview in android.

Add listview to your layout

<ListView
    android:id="@+id/lv_languages"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
</ListView>

Implement the java code

Finally add the following code to your MainActivity.java(or to the activity which you are using). The activity code is having the code for searching in listview inside onCreateOptionsMenu function. In the below code the search code is added on onQueryTextSubmit function which will do search operation on clicking submit button on keyboard, but in case if you want to do it on typing each character just copy paste the same code in onQueryTextChange function.

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    ListView lv_languages;

    ArrayAdapter<String> language_adapter;
    ArrayList<String> languagesarraylist;
    ArrayList<String> search_result_arraylist;

    private String keyword;

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

        //method for initialisation
        init();

        //setting array adaptet to listview
        lv_languages.setAdapter(language_adapter);


    }

    private void init() {

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("CodesFor Languages");
        languagesarraylist = new ArrayList<>();
        search_result_arraylist = new ArrayList<>();

        //adding few data to arraylist
        languagesarraylist.add("SQL");
        languagesarraylist.add("JAVA");
        languagesarraylist.add("JAVA SCRIPT ");
        languagesarraylist.add("C#");
        languagesarraylist.add("PYTHON");
        languagesarraylist.add("C++");
        languagesarraylist.add("IOS");
        languagesarraylist.add("ANDROID");
        languagesarraylist.add("PHP");
        languagesarraylist.add("LARAVEL");

        // initialising array adapter

        language_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,languagesarraylist);

        lv_languages = (ListView) findViewById(R.id.lv_languages);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem search_item = menu.findItem(R.id.mi_search);

        SearchView searchView = (SearchView) search_item.getActionView();
        searchView.setFocusable(false);
        searchView.setQueryHint("Search");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {


            @Override
            public boolean onQueryTextSubmit(String s) {

                //clear the previous data in search arraylist if exist
                search_result_arraylist.clear();

                keyword = s.toUpperCase();

                //checking language arraylist for items containing search keyword

                for(int i =0 ;i < languagesarraylist.size();i++){
                    if(languagesarraylist.get(i).contains(keyword)){
                        search_result_arraylist.add(languagesarraylist.get(i).toString());
                    }
                }

                language_adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,search_result_arraylist);
                lv_languages.setAdapter(language_adapter);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                return false;
            }
        });


        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }
}

android-searchview-in-actionbar

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

One Comment

  1. Kursus Pemrograman October 10, 2016 Reply

Add a Comment

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