Xamarin: Using SearchView in Toolbar
This is step-by-step instruction how to use SearchView in Toolbar for Xamarin Android.
Step 1
Create and Add SearchView menu item to /menu/itemSearch.xml. Moreover, this menu item uses following drawable. So you have to download the icon and paste into /drawable
<?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/search"
android:icon="@drawable/Search"
android:title="search"
app:showAsAction="ifRoom|withText"
app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
Step 2
Create and Add Toolbar to /Main.xaml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F8F8F8"/>
<ListView
android:id="@+id/lstView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"/>
</LinearLayout>
Step 3
In OnCreate,
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.InflateMenu(Resource.Menu.itemSearch);
toolbar.MenuItemClick += (object sender, Android.Support.V7.Widget.Toolbar.MenuItemClickEventArgs e) =>
{
};
var search = toolbar.Menu.FindItem(Resource.Id.search);
var searchView = search.ActionView.JavaCast<Android.Support.V7.Widget.SearchView>();
}
Moreover, using SearchView comes from an external library, namely Support.v7. Used JavaCast<T>() in order to cast it correctly. JavaCast<T>() is needed to perform Java-side object casts. Therefore, we need code to end up looking something like this.
var search = toolbar.Menu.FindItem(Resource.Id.search);
var searchView = search.ActionView.JavaCast<Android.Support.V7.Widget.SearchView>();