How to Create SearchView in Android Studio

How to Create SearchView in Android Studio

In this article we will learn how to create SearchView in android studio. SearchView is a widget that enables the user to enter search query and then send the request to the search provider. After that it shows a list of suggestion or results.

Copy the following xml code in main activity xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context="com.example.abdelhamd.images.MainActivity">

  <android.support.v7.widget.SearchView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/searchView"
      android:layout_margin="30dp"
      android:background="@android:color/darker_gray"/>

</LinearLayout>

After that add the following code to the main activity java file.

public class MainActivity extends AppCompatActivity {
    private SearchView searchView = null;
    private SearchView.OnQueryTextListener queryTextListener;

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

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) findViewById(R.id.searchView);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        queryTextListener = new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {
                Log.i("onQueryTextChange", newText);
                return true;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.i("onQueryTextSubmit", query);
                return true;
            }
        };
        searchView.setOnQueryTextListener(queryTextListener);
    }
 
}

Now, run the app. You will find the result as the following image.

searchview android studio

Then open logCat in the bottom bar of android studio. In the search section of logCat type “onQueryTextSubmit” to show the search query text in logcat. Now try to type any words the user may search it.

You should see the query text as shown in the following image.

searchview query in logCat

Learn how to create AutoCpmpleteTextView in android studio.

SearchView Interface in android studio

Leave a Comment

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