How to Use SearchView in Android Toolbar

In this android programming source code example, we are going to explore how to use searchview in android toolbar.

Below is a step by step source code to use searchview in android toolbar.

activity_main.xml

<?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"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="@color/colorPrimaryDark">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <android.support.v7.widget.SearchView
                android:id="@+id/search"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                app:iconifiedByDefault="false"
                app:queryHint="Search" />
        </RelativeLayout>
    </android.support.v7.widget.Toolbar>
</RelativeLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import com.bluapp.androidview.R;

public class SearchViewActivity19 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_view19);
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment